Reputation: 6699
I am working with android, socketio (nkzawa). When I connect the first time is working perfectly. But then If I disconnect and try to make "another connection" the EVENT_CONNECT is never called.
Here I put some snippets
When I connect
Inside BeforeActivity
@Override
public void onResume() {
super.onResume();
socketManager = (socketManager) socketManager.Instance(this, UrlHelper.URL.replaceAll("\\{userId\\}", userId.toString());
}
Then I have class SocketManager that extends from GenericSocket where I have a variable (SocketManager) instance for a singleton
public static SocketManager Instance(SocketListener listener, String url) {
if (instance == null) {
instance = new socketManager(url);
instance.init();
}
socketManager.listener = (listener)listener;
return instance;
}
and the initialization of the socket is done in the class GenericSocket where I have a variable of type (com.github.nkzawa.socketio.client.Socket ) tcalled socket
protected void init() {
try {
socket = IO.socket(url);
socket
.on(com.github.nkzawa.socketio.client.Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
onConnect();
JSONObject connectionMessage = getConnectionMessage();
socket.emit(MESSAGE_JOIN, connectionMessage);
}
}).on(MESSAGE, new Emitter.Listener() {
@Override
public void call(Object... args) {
Object data = args[0];
if (data instanceof JSONObject) {
JSONObject json = (JSONObject) data;
try {
onMessage(json.get("content").toString());
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
} else {
onMessage(data.toString());
}
}
}).on(Constant.CONNECTION, new Emitter.Listener() {
@Override
public void call(Object... args) {
Object data = args[0];
if (data instanceof JSONObject) {
JSONObject json = (JSONObject) data;
try {
onMessage(json.get("content").toString());
}
catch(Exception ex) {
Log.e(TAG, ex.getMessage());
}
} else {
onMessage(data.toString());
}
}
}).on(com.github.nkzawa.socketio.client.Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
onDisconnect();
}
});
socket.connect();
}catch (Exception e){
Log.i("Socket connection error: ", e.getMessage());
}
//end socket connection
}
and when I disconnect
The disconnect is like this inside SocketManager class I have this method
public void disconnect() {
this.socket.disconnect();
this.socket=null;
SocketManager.instance = null;
}
Thank you
Upvotes: 5
Views: 4192
Reputation: 16473
Your code looks fine. Try putting this.socket.off() before socket.disconnect(). I had an issue where server was keeping my connection alive even after disconnect(), socket.off() worked for me.
Upvotes: 5