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.
In the first case, the Socket will automatically try to reconnect, after a given delay.
Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With