Skip to content Skip to sidebar Skip to footer

How Can I Check Socket.io Connect Or Disconnect On Android?

I connect to the node server with socketio.SocketIO running as a service.And, When Service restarts,opens socket.io without socket.io closure.That's a problem. A device making mult

Solution 1:

Check Socket is connected or not using socket.isConnected(). This will return true if socket is connected

Solution 2:

Its just an idea so i don't know the limitations. pls let me know.

You can ping the server to check if the connection is alive.

In android

socket.emit("ping","ping");
socket.on("pong",pingHandler); //EmitterListenerprivateEmitter.Listener pingHandler=newEmitter.Listener(){
 @Overridepublicvoidcall(final Object... args) {
            Log.d("SocketStatus","Connection is active");
           });
}

and make the server return response for the ping

socket.on("ping",function(data){
socket.emit("pong","pong"); //from your server ex.Node.js
});

Solution 3:

You can check the socket.connected property:

var socket = io.connect();

console.log('Connected status before onConnect', socket.socket.connected);

socket.on('connect', function() {
  console.log('Connected status onConnect', socket.socket.connected);
});

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

Another solution would be to catch disconnect events and track the status yourself.

Solution 4:

The following is an expansion/modification of Rafique Mohammed answer above. The correct way is to try to reconnect on client side.

Internet drops (server cannot communicate disconnection to client). Server crashes (server may/may not be able to tell client. Server Restart (server can tell but that just extra work). After reconnection you will also like to rejoin the room for seamless communication

publicvoidconnectAfterDisconnectSocket(String senderActivity) {

    newTimer().scheduleAtFixedRate(newTimerTask() {
        @Overridepublicvoidrun() {

            boolean isConnected = false;
            isConnected = mSocket != null && mSocket.connected();

            if (!isConnected) {

                SocketIOClient socketIOClient = newSocketIOClient();
                socketIOClient.connectToSocketIO();

                if (senderActivity.equals("A")) {
                    A.joinChatRoom(room);
                }

                if (senderActivity.equals("B")) {
                    B.joinChatRoom(room);
                }
            }
        }
    }, 0, 1000); //put here time 1000 milliseconds=1 second
}

Post a Comment for "How Can I Check Socket.io Connect Or Disconnect On Android?"