Socket.IO Connected User Count
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.
I am running the Node.js
and Socket.IO
server on a VMware Ubuntu server.
Why is this or is there a better method for finding out how many people are connected to the server?
Solution 1:
Just in case someone gets to this page while using socket.io version 1.0
You can get the connected clients count from
socketIO.engine.clientsCount
Need an answer and the above did not work for new version of socket.io
Solution 2:
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--; });
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!
Solution 3:
I have found the way to figure it out in version 1.3.7. There are three methods as follows:
io.engine.clientsCount
io.sockets.sockets.length
Object.keys(io.sockets.connected).length
Hope these can help someone with the same issue.:)