12

I need to be able to detect when a user has lost connection to the socket, it doesn't seem that socket.on("disconnect") is being called when I just close my laptop, so it doesn't run the ajax call that needs to run in order to update the database to mark the user as offline. How could I check if the connection has been closed or whatever?

5
  • I would propose having a listener, or a 'heartbeat' that checks the clients for a response from the server. That is what I do. Feb 7, 2012 at 19:50
  • 1
    I did this in a previous version of my website, though given enough users on at a given time it seems as it may just be kind of overload on the server, as far as number of requests goes, though it may be the best, and only option. Feb 7, 2012 at 19:56
  • socket.io uses a heartbeat, so I'm sure this is doable
    – EhevuTov
    Feb 8, 2012 at 7:08
  • Well when I figured out is that it does detect that it disconnects, it triggers the disconnect in the server file, however it isn't able to emit the disconnect to the page where it gets its instructions to fire the ajax call to update the database for what ever reason, so I need to figure a way to update the database from the server file, which im unsure of how to. Feb 8, 2012 at 16:53
  • You could do either a callback or a custom eventemitter + subscriber.
    – mtsr
    Feb 9, 2013 at 15:00

2 Answers 2

6

As mentioned here https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO, Socket.IO has it's own heartbeat implementation. But the defaults are a 25s interval and a 60s threshold for a lost connection.

So my advice: Set the defaults as you expect on testing. Otherwise you may miss the threshold.

Example:

socket.set("heartbeat timeout", 10);
socket.set("heartbeat interval", 5);
1
  • This should be the accepted answer. It works on the first time... In my case the timeout and interval are set in milliseconds so 10000 instead of 10... Perfect Thanks! Jul 26, 2016 at 12:18
2

we came across this too and as mentioned above use our own heartbeat timer.

For example the server will emit a heartbeat every 5 seconds (we simple send out server time). The client has an 11 second timeout so it has 2 chances to catch the heartbeat. If it receives the heartbeat we reset the timer. If we miss both heartbeats the timeout function is run and you do whatever you want there.

Fairly straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.