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));
+3
source to share
4 answers
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 "/".
+4
source to share
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]--;
});
+2
source to share