node.js socket.io room total of users

后端 未结 1 571
野的像风
野的像风 2021-01-25 06:10

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:



        
相关标签:
1条回答
  • 2021-01-25 06: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) });
    
    0 讨论(0)
提交回复
热议问题