Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to count clients in a room across all instances #507

Open
sgtraptor opened this issue Jul 13, 2023 · 1 comment
Open

How to count clients in a room across all instances #507

sgtraptor opened this issue Jul 13, 2023 · 1 comment

Comments

@sgtraptor
Copy link

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.

@darrachequesne
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants