node.js socket.io room total of users

2019-03-02 18:05发布

I'm trying to count the total number of users in a specific room and broadcast it to all the people in that room.

Here is what I have but I get an error:

var clients = io.sockets.clients(cc.lowerCase(data.roomname)).length;
         io.sockets.in(cc.lowerCase(data.roomname)).emit('updatetotal', { total: clients });

ERROR:

TypeError: Object #<Namespace> has no method 'clients'

Thanks.

1条回答
贼婆χ
2楼-- · 2019-03-02 18:41

Since socket.io 1.0 its API was significantly changed so the old code might not work.

To get the number of clients in a room you can use this function:

var getUsersInRoomNumber = function(roomName, namespace) {
    if (!namespace) namespace = '/';
    var room = io.nsps[namespace].adapter.rooms[roomName];
    if (!room) return null;
    var num = 0;
    for (var i in room) num++;
    return num;
}

or more laconically:

var getUsersInRoomNumber = function(roomName, namespace) {
    if (!namespace) namespace = '/';
    var room = io.nsps[namespace].adapter.rooms[roomName];
    if (!room) return null;
    return Object.keys(room).length;
}

This function takes two agruments:

  • roomName
  • namespace (optional) default = '/'

To send message to users of this room only use .to method:

io.to(yourRoomName).emit('updatetotal', { total: getUsersInRoomNumber(yourRoomName) });
查看更多
登录 后发表回答