问题
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));
回答1:
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 "/".
回答2:
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]--;
});
回答3:
this works for version 3
io.sockets.adapter.rooms.get(roomName).size
回答4:
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
to rooms[room]
, because variable clients holds all connection inside sockets
variable.
回答5:
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);
}
来源:https://stackoverflow.com/questions/31468473/how-to-get-socket-io-number-of-clients-in-room