2
votes

I am now using socket.io with multiple nodes hence I started using the socket.io-redis adapter (https://github.com/socketio/socket.io-redis) to help me sync between nodes.

I would like to get a list of all the rooms on the server and a corresponding number of clients in each room efficiently.

At any one time I may have thousands of rooms and would like to get a count quickly of each room.

To get a list of all the rooms I would do:

io.of('/').adapter.allRooms((err, rooms) => {
  console.log(rooms); // an array containing all rooms (accross every node)
});

This returns a list of all the rooms, but at this point I am unsure how many connections each user has.

I could then run the next query to get the count for each room individually:

//query the first room, second room and so on...
io.in('firstroom').clients((err, clients) => {
  console.log(clients); // an array containing socket ids in 'room3'. Aggregate them to get the count
});

This seems very inefficient as I will be making so many calls to get the count individually. Is there a more efficient way than this to get a list of all the rooms with an associated count of connections? I have looked into modifying the adapter code but I do not really understand the code all that well to make any changes.

1

1 Answers

0
votes

Did you find a solution?

It seems that io.sockets.adapter.rooms returns the rooms together with the number of clients connected. Not sure whether it works in a redis-adapter environment however.

For example 2 person connected to 'someroom', io.sockets.adapter.rooms returns the following

{ someroom: Room { sockets: { 'dypabpHYTZii0F-bAAAC': true, GtGoSvP5yCOrQoMMAAAD: true }, length: 2 }, 'dypabpHYTZii0F-bAAAC': Room { sockets: { 'dypabpHYTZii0F-bAAAC': true }, length: 1 }, GtGoSvP5yCOrQoMMAAAD: Room { sockets: { GtGoSvP5yCOrQoMMAAAD: true }, length: 1 } }