2

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.

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753

1 Answers1

2

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);
Oleg
  • 22,300
  • 9
  • 68
  • 84
  • Unfortunately, at the time of this post, the documentation site is down. Regardless the documentation you refer to is outdated. It seems the current `socket.rooms` is an object rather than an array. However we ( may ) also have `socket._rooms` as an array in the future, albeit for less than a month now, from the [current source](https://github.com/socketio/socket.io/blob/master/lib/socket.js#L60). `socket.rooms` has been an object for [over a year](https://github.com/socketio/socket.io/blob/1.4.7-pre/lib/socket.js#L58). – Nolo Feb 24 '17 at 08:00
  • @Nolo yes, this is an object, and it was an object at the time of writing this post. Thanks for the tip. I edited my post to make it more clear – Oleg Feb 24 '17 at 08:23