I have an application that can support multiple chat rooms. I am trying to figure out how to capture which specific room a user disconnected from when they close the browser tab so I can update how many users are joined in a room on the client side. Right now it seems it's only possible to listen to the disconnect on a global level. If I get the disconnect event, I can loop through all the rooms the user belongs to via io.sockets.manager.roomClients[socket.id], calculate the number of users in the room with io.sockets.clients(room).length and emit that to each room. It seems silly to recalculate the number of people in a room if I don't know for sure that this user left that room.
In addition, I notice that in the disconnect event, io.sockets.clients(room) will show the disconnected user still in the array...I have to set a timeout of 2 seconds before that user is no longer in the array. Is this a known issue? He still shows disconnected:false as well so I am not able to go by that property.
Here is what I have so far:
socket.on('disconnect', function(){
//find all rooms this disconnected user belongs too
var rooms = io.sockets.manager.roomClients[socket.id];
for(var room in rooms){
room = room.replace('/','');
if(room){
//rooms tend to keep the count around for a while, needs a timeout before user is removed from room
setTimeout(function(){
socket.broadcast.to(room).emit('count', io.sockets.clients(room).length);
}, 2000);
}
}
});