how to get socket.io number of clients in room?
15,081
Solution 1
this works for version 3
io.sockets.adapter.rooms.get(roomName).size
Solution 2
To get the number of clients in a room you can do the following:
function NumClientsInRoom(namespace, room) {
var clients = io.nsps[namespace].adapter.rooms[room];
return Object.keys(clients).length;
}
This variable clients will hold a object where each client is a key. Then you just get the number of clients (keys) in that object.
If you haven't defined a namespace the default one is "/".
Solution 3
Have a counter variable to keep count, increase when someone joins and decrease when people disconnect.
io.on('connection', function (socket) {
var numClients = {};
socket.on('join', function (room) {
socket.join(room);
socket.room = room;
if (numClients[room] == undefined) {
numClients[room] = 1;
} else {
numClients[room]++;
}
});
socket.on('disconnect', function () {
numClients[socket.room]--;
});
Solution 4
This work for me.
// check if your room isn't undefined.
if (io.sockets.adapter.rooms['your room name'])
{
// result
console.log(io.sockets.adapter.rooms['your room name'].length);
}
Solution 5
this work for me
io.in('yourRoom').allSockets().then(result=>{
console.log(res.size) })
Author by
yathavan
Updated on June 26, 2022Comments
-
yathavan over 1 year
my socket.io version 1.3.5
I want to get number of clients in particular room.
This is my code.
socket.on('create or join', function (numClients, room) { socket.join(room); });
I use this code for get clients in room :
console.log('Number of clients',io.sockets.clients(room));