0

I've been struggling to find an efficient way to get the number of clients conencted to a room in socket.io. I've been advised to look into this thread: How to get room's clients list in socket.io 1.0 however none of the solutions currently work in this thread besides the one that checks for every single conencted socket and their rooms to be able to display a single room's cliens.

Therefore, I need to ask once more: what is the (urrently) most efficient way to get the (number of) clients in a room in socket.io?

Community
  • 1
  • 1
Mia
  • 6,220
  • 12
  • 47
  • 81
  • Can't you keep a count when a new user connects? And handle it appropriately when some user disconnects. It works, any issues with it? – Aravind Nov 09 '14 at 17:39
  • @aravind I can of course handle this manually in many ways, but I would love to learn about the most optimal way (currently) to handle this. Since socket.io does not have a full and up to date documentation/api anywhere, it's the best to ask here. – Mia Nov 09 '14 at 19:02
  • Zettam: I used socket a long time ago, and I used the basic api only. :) I would like to know of a good way too! – Aravind Nov 10 '14 at 03:19
  • I'd suggest make a simple app that sends a msg to everyone in a chat room and then just step through that code in the debugger and you will quickly see how socket.io keeps track of who is in a given chat room (since it has to know who's in every room in order to send to them all). It's likely an array of connections somewhere. – jfriend00 Nov 10 '14 at 03:25

1 Answers1

0

io.nsps[yourNamespace].adapter.rooms[roomName] // default namespace is '/'

returns the object of clients with a boolean value or undefined if there is no clients. In the most of the cases you can get the length of this object with

Object.keys(io.nsps[yourNamespace].adapter.rooms[roomName]).length

but it only will work if there is at least one client connected, due to the undefined returned.

If you're not using any specific namespace, you can use io.sockets.adapter.rooms[roomName] instead.

By default, when a client disconnects, it leaves the room, then this way has worked for me.