gpt4 book ai didi

socket.io - socket io v1 房间内的客户端数量

转载 作者:行者123 更新时间:2023-12-05 01:03:42 25 4
gpt4 key购买 nike

我刚开始玩 socket.io 并尝试制作一些 super 简单的东西,比如人们连接到房间。

我希望这能给我房间里的客户数量

io.sockets.on('connection', function (socket){
socket.on('create or join', function (channel) {
var numClients = io.sockets.clients(channel).length;
...
}
})

但它返回一个错误: Object #<Namespace> has no method 'clients'因为 V.1 中发生了一些变化。经过一些搜索,我用另一个替换了回调:
    var clients = io.sockets.adapter.rooms[channel];
var numClients = 0;
if (typeof clients !== 'undefined'){
numClients = clients.length;
}

p(numClients); // p is just a wrapper on console.log()
p(clients);
socket.join(channel);
socket.emit('created', channel);

但无论我连接多少次,我的客户端数量都是 0:
0
undefined
0
[ hSxLuOqrm5bX4UxmAAAA: true ]
0
[ hSxLuOqrm5bX4UxmAAAA: true, '2bjYS0lrUFySPM1OAAAB': true ]

我做错了什么?

附言以下是获取房间内客户数量的方法:
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;

最佳答案

这是因为 clients array 不是使用索引键存储套接字,而是使用字符串键(如对象)。

为了演示这一点,请查看以下代码:

var clients = [];
clients.somekey1 = true;
clients.somekey2 = true;

console.log(clients.length);
console.log(clients);

这是输出:
0
[ somekey1: true, somekey2: true ]

这个数组的实际长度是 0尽管其中有属性。所以你应该考虑 clients数组作为对象,因此可以使用以下代码行计算此“对象”中的客户端数量:
var numClients = Object.keys(clients).length;

From the MDN :

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).



而这正是我们所需要的。

关于socket.io - socket io v1 房间内的客户端数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com