user5191605
user5191605

Reputation:

detect socket.io disconnect and destroy events client side

I have html page sent by node.js server and socket.io component that connects to that server like this:

var socket = io();

Also several socket events:

socket.on('server-message', function(type, content) {
    ...
});

socket.on('server-update', function(type, content) {
    ...
});

The problem is that in the moment server is stopped, i get client side errors:

https://example.com/socket.io/?EIO=3&transport=polling&t=LptmQyC net::ERR_CONNECTION_REFUSED

Once server is started again it crashes in a 30 seconds after.

It looks like i could use a detection if server is not available anymore and just destroy all socket related events, then reconnect by page refresh or some button.

Maybe someone could help me with this.

Upvotes: 1

Views: 3110

Answers (1)

Mevia
Mevia

Reputation: 1564

I dont believe that much can be done about the error, its internal socket.io error that is a result of unsuccessful server polling.

For better understanding, once connection is severed, socket.io goes into ajax polling and will try to reconnect as soon as possible (meaning as soon as server is up again).

Server crash after reconnect on the other hand can be addressed very easy. The code you presented is only functional in terms of how to connect, you are missing handlers for disconnect and optionally - reconnect.

I will show you how you can add to this code to manage disconnects (and prevent server crashes after bringing it back up).

First of all connect to server:

var socket = io();

Create a disconnect event right after (btw its also a code for server side disconnect event):

socket.on('disconnect', function() {
    destroy_socket_events();
});

Create function that will destroy all your listeners:

var destroy_socket_events = function() {
    socket.off('disconnect');
    socket.off('server-message');
    socket.off('server-update');
    // add all other socket events that you have in here ...
};

Now what is going to happen is this:

  • connection is made
  • server is stopped
  • client triggers disconnect event
  • function destroys all of your socket listeners
  • server is back up
  • client reconnects (socket.io will do it because of the polling)
  • no listener is ever triggered at that point

So you can safely reinitialize all of your code and attach listeners again properly.

Upvotes: 1

Related Questions