socket.io/node.js detecting if server is down

Is there something that I can do on the client side to detect that the socket.io websocket is not available? Something along the lines of:

  • server starts as per usual
  • clients connect
  • messages are sent back and forth between server and client(s)
  • server shuts down (no longer available)
  • warn the connected clients that the server is not available

I tried to add the 'error' and 'connect_failed' options on the client side but without any luck, those didn't trigger at all. Any ideas from anyone how I can achieve this?

The disconnect event is what you want to listen on.

var socket = io.connect();

socket.on('connect', function () {
  alert('Socket is connected.');
});

socket.on('disconnect', function () {
  alert('Socket is disconnected.');
});

If you want to be able to detect that the client was not able to connect to the server, then try using connect_error. This works for me with socket.io-1.3.5.js. I found this in http://stackoverflow.com/a/28893421/2262092.

Here's my code snippet:

var socket = io.connect('http://<ip>:<port>', {
    reconnection: false
});
socket.on('connect_error', function() {
    console.log('Failed to connect to server');
});