Skip to content

Commit

Permalink
fixed the issue of not handling when the user gets disconnected from …
Browse files Browse the repository at this point in the history
…the server
  • Loading branch information
sanchitgarg1909 committed May 21, 2016
1 parent 8f66b94 commit 3dab919
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public class MainFragment extends Fragment {
private String mUsername;
private Socket mSocket;

private Boolean isConnected = true;

public MainFragment() {
super();
}
Expand All @@ -67,6 +69,8 @@ public void onCreate(Bundle savedInstanceState) {

ChatApplication app = (ChatApplication) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("new message", onNewMessage);
Expand All @@ -90,6 +94,9 @@ public void onDestroy() {
super.onDestroy();

mSocket.disconnect();

mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("new message", onNewMessage);
Expand Down Expand Up @@ -259,6 +266,37 @@ private void scrollToBottom() {
mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
}

private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(!isConnected) {
mSocket.emit("add user", mUsername);
Toast.makeText(getActivity().getApplicationContext(),
R.string.connect, Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};

private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
isConnected = false;
Toast.makeText(getActivity().getApplicationContext(),
R.string.disconnect, Toast.LENGTH_LONG).show();
}
});
}
};

private Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
<string name="action_send">Send</string>
<string name="prompt_message">Message</string>

<string name="connect">Connected</string>
<string name="disconnect">Disconnected, Please check your internet connection</string>
<string name="error_connect">Failed to connect</string>

<!-- messages -->
Expand Down

0 comments on commit 3dab919

Please sign in to comment.