5

I have the following abridged code:

io.on('connection', function(client) {
    client.uuid = uuid.v4();
    // add client object to server...

    console.log('socket.io:: client connected ' + client.uuid );

    client.on('disconnect', function() {
        console.log('socket.io:: client disconnected ' + client.uuid );
        // remove client object from server...
    });
});

If I open up this page in the browser, everything seems fine. If I refresh the page, it will fire disconnect and then connection. However, if I refresh fast enough, there are times where disconnect doesn't get called and thus client data doesn't get cleaned from the server. Is there any way to protect from this?

Edit: reword reconnect -> connection

Moo
  • 3,369
  • 4
  • 22
  • 41
  • There's never any guarantee that the browser will have time to send a request to the server, be it with ajax or sockets. The browser waits for no man, it reloads/redirects when it can, and you can't stop or delay it *(as that would be really annoying for users)* – adeneo Dec 23 '15 at 03:57
  • 2
    The fix is usually to poll from the server, to see if the user is still there, socket.io does this automagically with heartbeats, and there's probably a `leave` or `unsubscribe` event serverside that fires when there's no response from the client – adeneo Dec 23 '15 at 04:01
  • Does `reconnect` takes place if you refresh too fast ? I don't think so.. – Rayon Dec 23 '15 at 04:12
  • You may be able to figure out what happens with the orphaned connection by turning on debug for node – Clay Dec 23 '15 at 04:18
  • 1
    I left the server on for a bit and I see that after ~30-60 seconds I saw `disconnect` events firing. @adeneo do you want to write your comment as an answer so I can accept it? – Moo Dec 23 '15 at 04:24
  • I really don't know what the working code looks like, but why don't you post an answer with what works for you, and just accept your own answer. – adeneo Dec 23 '15 at 04:28

2 Answers2

2

The same question was answered here.

TL;DR You can use those options on the client:

const socket = io({
  transports: ['websocket'],
  upgrade: false
});

This will prevent socket.io from using the HTTP polling method at all, which causes the issues. I used this trick successfully on v4.

simlmx
  • 999
  • 12
  • 17
1

As adeneo mentioned, socket.io has heartbeats which automatically check to see if a client is still connected. The disconnect code is fired if it detects the client is actually gone. After replicating my original issue, I tried leaving the server on, and about 30 seconds later, the "dead" clients were being removed. So to solve the issue, you just have to wait. Socket.io takes care of everything on its own.

Community
  • 1
  • 1
Moo
  • 3,369
  • 4
  • 22
  • 41