5

How can you get a list of all clients in a room when using Socket.io 2.0?

There are a lot of related questions, but none are for version 2.0 or answer this question. The closest answer is for 2.0, but only explains how to get a list of clients when using Redis, which is not a requirement for using socket.io.

Don P
  • 60,113
  • 114
  • 300
  • 432
  • @LW001 - it's not. That is from 2014 about a pre 2.0 version. The accepted answer does not work in v2.0. The accepted answer is `io.sockets.adapter.rooms` which simply returns a list of room objects with a user count, not a specific list of users (ie the socket IDs socket.io generates). – Don P Oct 02 '17 at 19:22
  • @DonP, Then the normal thing to do is to post an answer on the other question with a solution under the newer version of the software. As it is, that question, is a superset of your question, as yours only asks about 2.0, not *all* versions, like the other question. The fact that the accepted answer doesn't work on the newer version is worth a comment, so others know, but doesn't justify a new question asking the same thing. The fact that an answer is accepted only indicates that it worked for the OP at the time it was accepted. – Makyen Oct 04 '17 at 00:32
  • Possible duplicate of [how to list rooms on socket.io nodejs server](https://stackoverflow.com/questions/6631501/how-to-list-rooms-on-socket-io-nodejs-server) – Makyen Oct 04 '17 at 00:43

2 Answers2

9

Found it, the answer was buried in Socket.io's docs under "namespace", not "room".

For example, if you are in the namespace "/chat" and want all clients in the room "general", you can do this:

io.of('/chat').in('general').clients((error, clients) => {
  if (error) throw error;

  // Returns an array of client IDs like ["Anw2LatarvGVVXEIAAAD"]
  console.log(clients); 
});
Don P
  • 60,113
  • 114
  • 300
  • 432
2

https://socket.io/docs/server-api/#namespace-clients-callback

io.of('/').in('room name').clients((error, clients) => {
  if (error) throw error;
  console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});

This is the for the default namespace. I mean without namespace.

Taki Elias
  • 127
  • 1
  • 7