Reputation: 3675
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
Upvotes: 6
Views: 1990
Reputation: 1333
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.
Upvotes: 3
Reputation: 3675
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.
Upvotes: 2