How to get socket.io number of clients in a room?
my socket.io version is 1.3.5
I want to get the number of clients in a certain room.
This is my code.
socket.on('create or join', function (numClients, room) {
socket.join(room);
});
I am using this code to get clients in a room:
console.log('Number of clients',io.sockets.clients(room));
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;
}
These variable clients will contain an 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 is "/".
Have a counter variable to keep the count, increase when someone joins and decreases 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]--;
});
In socket.io ^ 1.4.6
function numClientsInRoom(namespace, room) {
var clients = io.nsps[namespace].adapter.rooms[room].sockets;
return Object.keys(clients).length;
}
You need to add .sockets
in rooms[room]
as clients variables contain all connections inside a variable sockets
.
This job is 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);
}