Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deal with socket disconnection and reconnection. #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/client/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ export const removeUser = createAction('remove user');

export const newMessage = createAction('new message');
export const sendMessage = createAction('send message');

export const ws_disconnected = createAction('ws is disconnected');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't setup ESLint, but I prefer camelcase, not snake case.

export const connecting = createAction('connecting');
14 changes: 11 additions & 3 deletions src/client/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,27 @@ import { connect } from 'react-redux';
import { AppBar, FlatButton } from 'material-ui';
import { Welcome, Room } from './views';
import { logout } from './actions';
import CircularProgress from 'material-ui/CircularProgress';
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can import CircularProgress in the first line like...

import { AppBar, FlatButton, CircularProgress } from 'material-ui';


class App extends Component {
handleLogout() {
this.props.dispatch(logout());
}

render() {
const { username } = this.props;
const { username, connecting } = this.props;

let body, right;
if (username) {
body = <Room />;
right = <FlatButton label="Logout" onTouchTap={this.handleLogout.bind(this)} />;
if (connecting) {


body = <div style={{ display: 'flex' }}><div style={{ flex: 1 }}/><CircularProgress /><div style={{ flex: 1 }}/></div>;
}
else {
body = <Room />;
}
right = <FlatButton label="Logout" onTouchTap={this.handleLogout.bind(this) } />;
} else {
body = <Welcome />;
}
Expand Down
10 changes: 7 additions & 3 deletions src/client/reducers.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { combineReducers } from 'redux';
import { createReducer } from 'redux-act';
import {
login, logout, addUser, removeUser, newMessage
login, logout, addUser, removeUser, newMessage, connecting
} from './actions';

const initial = {
app: {
username: null
username: null,
connecting: false
},
users: {},
messages: {
Expand All @@ -20,7 +21,10 @@ const app = createReducer({
return { ...state, username: payload.username };
},
[logout]: (state, payload) => {
return { ...state, username: null };
return { ...state, username: null, connecting: false };
},
[connecting]: (state, payload) => {
return { ...state, connecting: payload.connecting };
},
}, initial.app);

Expand Down
95 changes: 72 additions & 23 deletions src/client/sagas.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import io from 'socket.io-client';
import { eventChannel } from 'redux-saga';
import { eventChannel, END } from 'redux-saga';
import { fork, take, call, put, cancel } from 'redux-saga/effects';
import {
login, logout, addUser, removeUser, newMessage, sendMessage
login, logout, addUser, removeUser, newMessage, sendMessage,
connecting, ws_disconnected
} from './actions';

function connect() {
const socket = io('http://localhost:3000');
return new Promise(resolve => {
const socket = io('http://localhost:3000', {
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax': 5000,
'reconnectionAttempts': 5
});
return new Promise((resolve, reject) => {
socket.on('connect', () => {
resolve(socket);
});
});
socket.on('reconnect_failed', (err) => {
reject(new Error('ws:reconnect_failed '))
});
}).then(
response => ({ socket: response })
).catch(
error => ({ socket, error })
);
}

function subscribe(socket) {
Expand All @@ -26,24 +39,34 @@ function subscribe(socket) {
emit(newMessage({ message }));
});
socket.on('disconnect', e => {
// TODO: handle
emit(END)
});
return () => {};
return () => { };
});
}

function* read(socket) {
const channel = yield call(subscribe, socket);
while (true) {
let action = yield take(channel);
yield put(action);
try {
while (true) {
let action = yield take(channel);
yield put(action);
}
}
finally {
yield put(ws_disconnected())
}
}

function* write(socket) {
while (true) {
const { payload } = yield take(`${sendMessage}`);
socket.emit('message', payload);
try {
while (true) {
const { payload } = yield take(`${sendMessage}`);
socket.emit('message', payload);
}
}
finally {

}
}

Expand All @@ -52,20 +75,46 @@ function* handleIO(socket) {
yield fork(write, socket);
}

function* flow() {
while (true) {
let { payload } = yield take(`${login}`);
const socket = yield call(connect);
socket.emit('login', { username: payload.username });
function* flow(username) {
try {
while (true) {
yield put(connecting({ connecting: true }));
const { socket, error } = yield call(connect);
yield put(connecting({ connecting: false }));

if (error) {
yield call([socket, socket.disconnect]);
yield put(logout());
break;
}

const task = yield fork(handleIO, socket);
if (socket) {
socket.emit('login', { username });

const task = yield fork(handleIO, socket);

let action = yield take([`${logout}`, `${ws_disconnected}`]);
yield cancel(task);
socket.emit('logout');
yield call([socket, socket.disconnect]);
if (action.type == logout().type) {
break;
}
}
}
}
finally {

let action = yield take(`${logout}`);
yield cancel(task);
socket.emit('logout');
}
}

export default function* rootSaga() {
yield fork(flow);
let myFlow;
while (true) {
let {payload} = yield take(`${login}`);
if (myFlow) {
yield cancel(myFlow);
}
myFlow = yield fork(flow, payload.username);
}
}