I’m working on a chat application with Node.js and Socket.io, and on disconnect, the remaining user receives an alert saying that their partner disconnected.
The problem is that every once in a while, Socket.io automatically disconnects then reconnects. My chat application is triggering the alert, even though the partner hasn’t really disconnected.
Code:
var clients = {};
var soloClients = [];
io.sockets.on('connection', function (socket) {
//Session start
socket.on('sessionStart', function () {
clients[socket.id] = socket;
soloClients.push(socket.id);
var searchClients = function(){
if(soloClients.length > 1){
var rand = Math.floor(Math.random() * soloClients.length);
if(soloClients[rand] && soloClients[rand] != socket.id){
if(clients[soloClients[rand]]){
var you = clients[socket.id];
var partner = clients[soloClients[rand]]
clients[partner.id]['partner'] = you.id;
clients[you.id]['partner'] = partner.id;
soloClients.splice(soloClients.indexOf(you.id), 1);
soloClients.splice(soloClients.indexOf(partner.id), 1);
partner.emit('partnerConnect', null);
socket.emit('partnerConnect', null);
}
else{
soloClients.splice(rand, 1);
searchClients;
}
}
else{
searchClients();
}
}
};
searchClients();
});
//On disconnect
socket.on('disconnect', function(){
soloClients.splice(soloClients.indexOf(socket.id), 1);
if(clients[socket.id]){
if(clients[clients[socket.id]['partner']]){
clients[clients[socket.id]['partner']].emit('partnerDisconnect', null);
}
delete clients[socket.id];
}
});
});
I was wondering if there is any way to solve this.
Thanks!
It turns out that this behavior isn’t supposed to happen, it was just a bug in that version. This bug has been fixed in the latest version.