一尘不染

在 socket.io 的聊天室中获取多少人

javascript

我现在有这段代码设置了缺口和余地:

io.sockets.on('connection', function(client){
    var Room = "";
    client.on("setNickAndRoom", function(nick, fn){
        client.join(nick.room);
        Room = nick.room;
        client.broadcast.to(Room).emit('count', "Connected:" + " " + count);
        fn({msg :"Connected:" + " " + count});
    });

我想知道我如何才能有多少人连接到特定的聊天室…例如Room.length

客户端 :

function Chat(){
    this.socket = null;
    this.Nickname = "";
    this.Room = "";
    var synched = $('#syncUp');
    this.Connect = function(nick, room){ 
        socket =  io.connect('http://vybeing.com:8080');    
        Nickname = nick;
        Room = room;
        //conectarse
        socket.on('connect',function (data) {
            socket.emit('setNickAndRoom', {nick: nick, room: room}, function(response){
                $("#connection").html("<p>" + response.msg + "</p>");
            });
        });
}

我发现了这一点,但给出了未定义的内容:

count = io.rooms[Room].length;

阅读 845

收藏
2020-07-11

共1个答案

一尘不染

对于socket.io版本> = 1.0:

请注意,房间成为具有.length1.4属性的实际类型,因此1.4.x方法从现在开始应该是稳定的。当然,禁止对该类型的API进行重大更改。

计算所有连接到的客户端’my_room’:

1.4+:

var room = io.sockets.adapter.rooms['my_room'];
room.length;

1.3.x:

var room = io.sockets.adapter.rooms['my_room'];
Object.keys(room).length;

1.0.x至1.2.x:

var room = io.adapter.rooms['my_room'];
Object.keys(room).length;

这是假设您在单个节点(而不是集群)上使用默认的Room适配器运行。如果您在集群中,事情会更加复杂。

其他相关示例:

计算连接到服务器的所有客户端:

var srvSockets = io.sockets.sockets;
Object.keys(srvSockets).length;

计算连接到名称空间的所有客户端’/chat’:

var nspSockets = io.of('/chat').sockets;
Object.keys(nspSockets).length
2020-07-11