-
Notifications
You must be signed in to change notification settings - Fork 487
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
Comments
Hi! There are a couple of ways to do this:
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);
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
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.
The text was updated successfully, but these errors were encountered: