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 sockets.io server on a vmware ubuntu server.

Does anyone know why this is or has a better method for finding out how many people are connected to the server?

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!

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

Also take a look into:

io.sockets.manager.connected

It's a clean list of key value pairs (socket id and connection state?)

I'm using socket.io 0.9.10 and the following code to determine the number of sockets:

var socketIO =  require('socket.io').listen( .....
var numberOfSockets = Object.keys(socketIO.connected).length;

Not sure how accurate this number reacts to the various edge-cases, but 'til now it seems accurate: every browser connecting increases the number, every browser closed decreases it.

Why use an (implicit global) variable when you could always filter the array, that is returned by calling the clients() method.

function filterNullValues (i) {
  return (i!=null);
}
io.sockets.clients().filter(filterNullValues).length;

I am currently using Socket.io v1.3.6 and have found that this works. It gives an accurate number when users connect and when they disconnect:

io.sockets.sockets.length

Like so:

var io = require('socket.io').listen(server);
io.on('connection', function(socket) {
  console.log(io.sockets.sockets.length);
  socket.on('disconnect', function() {
    console.log(io.sockets.sockets.length);
  });
});