Node.js & Socket.IO - issue of numbers

Consideration of a multitasking application. Users can join several rooms ( socket.join(room) ), users can leave the room ( socket.leave(room) ).

When the socket leaves the room, I notify other participants in the room. If the socket is currently in 3 rooms and it suddenly disconnects from the website without leaving the room properly, how can I notify those rooms that you have left?

If I work with the disconnect disconnect event, the user will no longer be in any room at this point. The only way to keep a separate array of users, or is there some kind of smart way that I haven't thought about?

+7
source share
2 answers

During a disconnect event, the socket is still available for 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 required, as socket.io will automatically disable rooms on a disconnect event. However, you can use this method if you want to perform a specific action.

+5
source

I assume that the socket is a long-lived object in your node process. If this is the case, you can easily add a user link to your socket object when the user connects. When you get a socket disconnect, you don’t need to look for the user with whom the session is connected, as it will be there.

when connecting or login:

 socket.user = yourUser; 

when disconnected:

 socket.on('disconnect', function(){ socket.leave(room, socket.user); } 

see here an example of adding properties to a socket object and a client with a single client:

http://psitsmike.com/2011/09/node-js-and-socket-io-chat-tutorial/

0
source

All Articles