socketio/socket.io-redis-adapter

How to count clients in a room across all instances

sgtraptor opened this issue · 3 comments

Hi,
I have a problem with counting all clients connected to a specific room. We are using Redis adapter and we seem to be getting different results on both of our ECS tasks. I can call io.of("/").adapter.rooms.get(hash) but it seems to count clients in this room within one of the tasks. How can I get a number of clients connected to a room across all instances?

I've checked socket.io and socket.io redis adapter reference twice and I haven't found a proper solution. Sorry if this is dumb question, but nothing seems to work and this seems to me like an obvious "should be there" feature that probably is already implemented but I can't seem to find it.

Hi! There are a couple of ways to do this:

  • server.fetchSockets()
const sockets = await io.in("my-room").fetchSockets();

console.log(sockets.length);

Reference: https://socket.io/docs/v4/server-api/#serverfetchsockets

This is not the most efficient way, because it returns some additional attributes (id, handshake, rooms, data) for each socket, but this also allows to count the number of distinct users:

const sockets = await io.in("my-room").fetchSockets();
const userIds = new Set();

sockets.forEach((socket) => {
  userIds.add(socket.data.userId);
});

console.log(userIds.size);
  • server.serverSideEmit()
io.serverSideEmit("socketsCount", "my-room", (err, responses) => {
  const localCount = io.of("/").adapter.rooms.get("my-room").size;
  const totalCount = responses.reduce((acc, value) => acc + value, localCount);

  console.log(totalCount);
});

io.on("socketsCount", (room, cb) => {
  const count = io.of("/").adapter.rooms.get(room).size;
  cb(count);
});

Reference: https://socket.io/docs/v4/server-api/#serverserversideemiteventname-args