Reputation: 222511
I am using socket.io version 1 and I have the following problem.
I have an application, in which user can connect to different rooms. On disconnect event I want this user to notify that he left the rooms he connected to. (I know that on disconnect user leaves all rooms automatically, but I want to notify others that user left them.)
I looked into this list and have not found a simple way to do what I want. May be there is a better way to do this, but currently my solution is to find all rooms and in a loop sent to all people in each room. But neither io.sockets.manager, nor adapter can give me a list of rooms a client is connected to.
client.on('disconnect', function() {
// io.sockets.manager.roomClients[client.id];
// io.sockets.adapter.roomClients[client.id];
});
P.S. Seeing one wrong answer, I want to clarify. I know how to send message to people in the room. I want to solve another problem. If a user entered Room1
, Room2
, ...
, RoomN
and then disconnects, I want to send message to all people in these N
rooms.
Upvotes: 3
Views: 2241
Reputation: 23277
You can find all rooms a client is connected to with Socket#rooms
object (documentation):
io.on('connection', function(socket) {
//...
console.log(socket.rooms);
});
You can then easily send a message to each of these rooms in a loop.
Caveat: socket.join
method is async, so if you have something like:
socket.join('my room name');
console.log(socket.rooms);
it won't work as expected. Instead you should write:
socket.join('my room name', function() {
console.log(socket.rooms);
});
Edit:
If you want to get an array rather than object, you may do this:
Object.keys(socket.rooms);
Upvotes: 2