how to get socket.io number of clients in room?

為{幸葍}努か 提交于 2020-12-11 04:35:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!