Skip to content Skip to sidebar Skip to footer

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 conne

Solution 1:

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.');
});

Solution 2:

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');
});

Solution 3:

hit this bug during my development and noticed my event calls were doubling up every time i reset the server, as my sockets reconnected. Turns out the solution that worked for me, which is not duping connections is this

var socket = io.connect();

socket.on('connect', function () {

console.log('User connected!');

});

socket.on('message', function(message) {

console.log(message);

});

( Found this at https://github.com/socketio/socket.io/issues/430 by KasperTidemann )

Turns out, it was becuase I put the 'message' listener inside the 'connect' function. Seating it outside of the listener, solves this problem.

Cheers to Kasper Tidemann, whereever you are.

Moving on!!

Solution 4:

connect_error didn't work for me (using Apache ProxyPass and returns a 503).

If you need to detect an initial failed connection, you can do this.

var socket;
try {
    socket = io();
}
catch(e) {
    window.location = "nodeServerDown.php";
}

Redirects the user to a custom error page when the server is down.

If you need to handle a disconnect after you've connected once.

You do this:

socket.on('disconnect', function() {
    //whatever your disconnect logic is
});

Post a Comment for "Socket.io/node.js Detecting If Server Is Down"