简体   繁体   中英

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

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!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM