Socket.IO 连接用户数 [英] Socket.IO Connected User Count
问题描述
我终于让Socket.IO正常工作了,但是我遇到了一个奇怪的问题.
I finally got Socket.IO to work properly, but I have encountered a strange problem.
我不确定这是否是最好的方法,但我正在使用:
I am not sure if this is the best way, but I am using:
io.sockets.clients().length
这将返回连接到我的服务器的客户端数量.问题是在用户几次连接和断开连接后,数字开始保持高于应有的水平.
This returns the number of clients connected to my server. The problem is after a few connects and disconnects of users, the number starts to stay higher than it should be.
例如,如果我连接并请我的朋友连接,数字会上升,这是正确的.但是当我们开始断开连接并重新连接时,数量并没有减少.
For instance, if I connect and ask my friends to, the number goes up which is correct. But when we start to disconnect and reconnect the number does not decrease.
我在 VMware 上运行 Node.js 和 Socket.IO 服务器href="https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="nofollow noreferrer">Ubuntu 服务器.
为什么会这样,或者是否有更好的方法来找出有多少人连接到服务器?
Why is this or is there a better method for finding out how many people are connected to the server?
推荐答案
有一个 github 问题为了这.问题是,每当有人断开 socket.io 时,不会从数组中删除( splice ),而是简单地将值设置为null",因此实际上您的数组中有很多空值,这使您的客户端().length 比您在现实中拥有的连接更大.
There is a github issue for this. The problem is that whenever someone disconnects socket.io doesn't delete ( splice ) from the array, but simply sets the value to "null", so in fact you have a lot of null values in your array, which make your clients().length bigger than the connections you have in reality.
您必须以不同的方式管理客户的数量,例如类似的东西
You have to manage a different way for counting your clients, e.g. something like
socket.on('connect', function() { connectCounter++; });
socket.on('disconnect', function() { connectCounter--; });
这是一个思想嗡嗡声,为什么socket.io背后的人留下这样的东西,但最好在github问题中解释,我作为链接发布!
It's a mind buzz, why the people behind socket.io have left the things like that, but it is better explain in the github issue, which I posted as a link!
这篇关于Socket.IO 连接用户数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!