Considering a multi-chat application.
Users can join multiple rooms ( socket.join(room)
), users can leave a room ( socket.leave(room)
).
When socket is leaving a room I notify the other room participants. If the socket is currently in 3 rooms, and he suddenly disconnects from the website without leaving the rooms the proper way, how can I notify those rooms that the user has left ?
If I work with the on socket disconnect event, the user will no longer be in any room at that point. Is the only way keeping a separate array of users, or is there some clever way I haven't thought about?
Considering a multi-chat application.
Users can join multiple rooms ( socket.join(room)
), users can leave a room ( socket.leave(room)
).
When socket is leaving a room I notify the other room participants. If the socket is currently in 3 rooms, and he suddenly disconnects from the website without leaving the rooms the proper way, how can I notify those rooms that the user has left ?
If I work with the on socket disconnect event, the user will no longer be in any room at that point. Is the only way keeping a separate array of users, or is there some clever way I haven't thought about?
Share Improve this question edited Dec 21, 2012 at 3:58 Sushant Gupta 9,4685 gold badges45 silver badges49 bronze badges asked Dec 21, 2012 at 3:01 Gabriel GrayGabriel Gray 631 silver badge5 bronze badges 1- hmm, no matter what i seem to do there is always 2 users in the room according to socketio – r3wt Commented Feb 26, 2016 at 10:49
2 Answers
Reset to default 5During the disconnect event the socket is still available to your process. For example, this should work
io.socket.on('connection', function(socket){
socket.on('disconnect', function() {
// this returns a list of all rooms this user is in
var rooms = io.sockets.manager.roomClients[socket.id];
for(var room in rooms) {
socket.leave(room);
}
});
});
Although this is not actually necessary as socket.io will automatically prune rooms upon a disconnect event. However this method could be used if you were looking to perform a specific action.
I'm assuming that socket is a long lived object in your node process. If that's the case then you could easily add a reference to the user on your socket object when the user connects. When you get a socket disconnect, you don't need to look up the user the session is associated with as it will be there.
on connection or login:
socket.user = yourUser;
on disconnect:
socket.on('disconnect', function(){
socket.leave(room, socket.user);
}
see here for an example of adding properties to the socket object and a single room chat client:
http://psitsmike./2011/09/node-js-and-socket-io-chat-tutorial/