Data
Data

Reputation: 1357

Socket.IO - how to handle Node.js offline

Everything works great with different browsers connected to the same port chatting away, but when I close my Node server with ctrl+C, I get the following error in my browser:

GET http://my-url net::ERR_CONNECTION_REFUSED 

I've tried the following client-side callbacks:

socket.on('reconnect_attempt' ...
socket.on('message' ...

But they don't trigger, so I did a dirty hack which does work; using a timer to check the socket every second and if the node server goes down, then do a redirect:

setInterval(function(){ 
  if (socket.disconnected) window.open("http://otherurl","_self"); 
}, 1000);

Is there a better way to detect if a node server goes offline using client-side js code?

Upvotes: 2

Views: 1907

Answers (2)

Deyan Vitanov
Deyan Vitanov

Reputation: 784

I've found it! You just need to listen for error event (socket.io 0.9)

socket.on('error', function() {
      // handle server error here
      console.log('Error net::ERR_CONNECTION_REFUSED occured. Handle me');
});

This event was not documented in socket.io client 0.9 docs, which was strange

Upvotes: 0

Catalyst
Catalyst

Reputation: 3247

As per this other SO question How can I detect disconnects on socket.io?

Below is copied for quick reference:

socket.io has a disconnect event, put this inside your connect block:

socket.on('disconnect', function () {
    //do stuff
});

Upvotes: 2

Related Questions