Problem with socket listeners when the internet connection is turned off / turned on
I am developing android chat application using "io.socket:socket.io-client:0.8.1" android client and node js server. I really don't know whether it is a issue or problem with my code. I am initializing socket connection in singleton class.
public class SocketSingleton { public static Realm realm; private static Socket mSocket = null; SocketListners socketListners; public static Socket getSocketConnection(){
if(mSocket == null || mSocket.id() == null){
try {
realm = Realm.getDefaultInstance();
UserModel user = realm.where(UserModel.class).findFirst();
//Log.i("SOCKET CONNECTION ====>" , ChatVariables.getInstance().getAuthToken());
IO.Options opts = new IO.Options();
String authToken = URLEncoder.encode(user.getAuthToken(),"UTF-8");
opts.query = "authToken=" +authToken+ "&id="+user.getUserId();
mSocket = IO.socket(ServerUrl.CHAT_SERVER_URL, opts);
mSocket.connect();
mSocket.emit("defalultEvent", "");
}
catch (URISyntaxException e)
{
throw new RuntimeException(e);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return mSocket;
}else{
return mSocket;
}
}
and i have two activities Chat Layout Activity and GroupList Activity, in both the activites i am getting socket connection and adding listeners as follows
Everything works fine initially, when app launches and when it has active internet connection.The problem occurs when there is change occurs in network / internet or if you manually turn off and turn on back internet/wifi. In this case, socket object remains same but "socket object does not hold any listeners (socket.emit works fine, but not listener)"
`public class ChatLayoutActivity extends AppCompatActivity { private Socket mSocket; @Override protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat_layout);
//Getting socket conncetion
mSocket = SocketSingleton.getSocketConnection();
//Listeners
mSocket.on(EventConstants.GROUP_CHAT_LIST, groupChatList);
mSocket.on(EventConstants.FEED_CHAT_MESSAGE, feedChatMessage);
.
.
.
private Emitter.Listener EventConstants.FEED_CHAT_MESSAGE= new Emitter.Listener() {
@Override
public void call(Object... args) {
final JSONObject feedChatMessage= (JSONObject) args[0];
try {
// I parse data here
} catch (Exception e) {
Log.e("SOCKET_LISTENER", "ChatLayout Activity(groupChatList) " + e.getMessage());
}
}
};
} } }`
What i am missing..? and I have total 5 listeners(in both activities) and how can i properly write all listeners at one side
I have a chat application and I have same issues. When change or disconnect internet, The Socket's "on" is connecting after 10 - 20 seconds. But Emit method work nicely. Can you help us?