Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reconnect socket.io client on activity after auto-reconnect times out?

It is common for laptops to go to sleep. This causes the socket.io client to disconnect. When the user returns to the web app, the socket.io client doesn't try to reconnect (probably reconnection limit reached?). How do I tell the socket to reconnect if the user does some action?

For example, I'd like the emit function to check if the connection is active, and if not then try to reconnect.

Note: I only need the client-side JS code and I'm not using node.js.

like image 735
Tony Abou-Assaleh Avatar asked Jul 26 '12 10:07

Tony Abou-Assaleh


People also ask

Does Socket.IO auto reconnect?

In the first case, the Socket will automatically try to reconnect, after a given delay.

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.


2 Answers

In version 0.9 you could try to set the connect options object to some aggressive settings:

  var main = io.connect('/', {
    'reconnection delay': 100, // defaults to 500
    'reconnection limit': 100, // defaults to Infinity
    'max reconnection attempts': Infinity // defaults to 10
  });

Note that max reconnection attemps does not mean that the io client will stop to reconnect to the server after 10 failed attempts. If it was able to reconnect to the server 10 times and loses the connection for the 11th time, it will stop to reconnect.

See Socket.IO Configuration

like image 80
django Avatar answered Sep 20 '22 18:09

django


Socket instances have an inner 'socket' property, which in turn has connect() method that you can call. It's normally called automatically when you instantiate the object (controlled by the 'auto connect' option). The inner socket also have a boolean "connected" property which you can check if you're not sure what the state is. Like so:

sio = io.connect();
//... time passes ...
if (! sio.socket.connected) {
  sio.connect();
}

The connect() method checks to make sure that the socket isn't in the middle of trying to connect, though for some reason it doesn't check to see if it's already connected. Not sure what happens if you connect() an already-connected socket...

The source code for the client library is fairly clear and well commented, which is good since the README on github doesn't provide a whole lot of help. It's handy to use an un-minified version of the library while you're doing development so you can dig into the source.

like image 42
Dirk Bergstrom Avatar answered Sep 19 '22 18:09

Dirk Bergstrom