korujzade korujzade - 28 days ago 10
Android Question

How can I know that Android app reconnected to Socket.io?

I have an android application which connects to a socket and emits

connectionData
event on
onCreate
method.

// connect to socket
private Socket socket;
{
try {
socket = IO.socket(AppConfig.URL_SOCKET_IO);
} catch (URISyntaxException e) {
Log.e(LOG_TAG, "error");
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
// emit connect and connection data socket
socket.connect();
socket.emit("connectionData", currPlayer.getPlayerID());
}


On the server side, there is
activeSockets
HashMap which stores
<connectionData, socket>
data. When the internet connection is lost in the app, the server catches
disconnect
event and removes the socket from the HashMap. And when the app reconnects to the internet, it connects to the socket as well, but the app doesn't emit
connectionData
anymore as it only happens once the activity is created.

How can I detect that the app reconnected to the socket on the client side so that I can emit
connectionData
again?

Answer

Add an event listener:

socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
    @Override
    public void call(final Object... args) {
        socket.emit("connectionData", currPlayer.getPlayerID());
    }
});

See this Q&A for a list of other events.