Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
Tamas Avatar asked May 09 '13 03:05

Tamas


People also ask

Does Socket.IO reconnect after disconnect?

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

How do I know if a Socket is connected node?

var socket = io. connect(); console. log('check 1', socket. connected); socket.


2 Answers

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.');
});
like image 102
matthewtole Avatar answered Oct 14 '22 21:10

matthewtole


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 https://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');
});
like image 11
cbautista Avatar answered Oct 14 '22 20:10

cbautista