Android Nkzawa SocketIO disconnects and establishes a new connection

I work with android, socketio (nkzawa). When I connect, the first time it works fine. But then if I disconnect and try to make a “different connection”, EVENT_CONNECT is never called.

Here I put some fragments

When i plug in

Inside BeforeActivity

@Override public void onResume() { super.onResume(); socketManager = (socketManager) socketManager.Instance(this, UrlHelper.URL.replaceAll("\\{userId\\}", userId.toString()); } 

Then I have a SocketManager class that extends from GenericSocket, where I have a variable instance (SocketManager) for 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 socket initialization is done in the GenericSocket class, where I have a variable like (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 turn off

Disconnecting is like this inside the SocketManager class. I have this method

 public void disconnect() { this.socket.disconnect(); this.socket=null; SocketManager.instance = null; } 

thanks

+5
source share
1 answer

Your code looks great. Try putting this.socket.off () before socket.disconnect (). I had a problem when the server supported my connection even after disconnecting (), socket.off () worked for me.

+5
source

Source: https://habr.com/ru/post/1214342/


All Articles