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.

3
  • @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). Commented Oct 2, 2017 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. Commented Oct 4, 2017 at 0:32
  • Possible duplicate of how to list rooms on socket.io nodejs server Commented Oct 4, 2017 at 0:43

2 Answers 2

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); }); 
Sign up to request clarification or add additional context in comments.

4 Comments

What would you do if you're using the default namespace / ?
I figured it out. If anyone else is wondering the following works... io.of('/').in(room).clients((err, data)=> ...
You don't need the .of('/') - it will assume it
How can I use async and await with this?
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.

1 Comment

How can I use async and await with this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.