Socket.io Connected User Count

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!


I have found the way to figure it out in version 1.3.7. There are three methods as follows:

  1. io.engine.clientsCount
  2. io.sockets.sockets.length
  3. Object.keys(io.sockets.connected).length

Hope these can help someone with the same issue.:)


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


with socket.io 2.2.0 it's easier :

io.on('connection', function (socket) {
    console.log( socket.client.conn.server.clientsCount + " users connected" );
});

cheers