Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io recovery from disconnections

I have a chat with a server and a client in Socket.io. The client sends and receives messages to / from the server. In order to test a disconnection event, I pull out my Ethernet plug and reattach it after a few seconds.

After that sending messages from the client still works just fine and all previously sent messages during disconnection are resent successfully on both Chrome and Firefox.

For receiving however, it is OK for Chrome but not for Firefox which doesn't receive messages from the server anymore.

The question is what do I do to properly handle such network problems and make my chat robust?

like image 956
Gherman Avatar asked Nov 23 '18 16:11

Gherman


1 Answers

As stated in the docs and like you said, the socket should be reconnecting itself normally. Since you can send messages, it seems you are halfway reconnected.

There is a couple events that would be worth for you to add in order to see if nothing is out of the ordinary: reconnecting, reconnect_attempt, reconnect, reconnect_error and reconnect_failed.

If nothing comes out of this, what I would advise you to do would be to check if you are getting a disconnect event in your client and recall your connect function, so you get a brand new socket after the network is reestablished:

socket.on('disconnect', () => {
  // reconnect
})

From past experiences there was some dirty state stored in the socket object that could explain your issue, and it's worth it to start over with a clean one.


Note for people who do not need the socket-io client, there is also a little library that allows to do just that, reconnect gracefully in case your network drops and should work with a socket-io backend too, reconnecting-websocket.

like image 189
Preview Avatar answered Oct 24 '22 21:10

Preview