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.cli
Connected Users count in number with socket.io version - 1.3.7
io.on('connection', (socket) => {
console.log(io.sockets.server.httpServer._connections); //output in number
// or
console.log(io.sockets.server.engine.clientsCount); //output in number
});
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;
Tested using Socket.IO v2.3.0 using namespace, I found 4 locations having the clientCounts property (it's probably the same Server
object each time):
const socketio = require('socket.io');
const io = socketio(http_server);
const io_namespace = io.of('/foobar');
io_namespace.on('connection', function(socket)
{
console.log(socket.conn.server.clientsCount);
console.log(socket.server.engine.clientsCount);
console.log(io.engine.clientsCount);
console.log(io_namespace.server.engine.clientsCount);
});
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!
with socket.io 2.2.0 it's easier :
io.on('connection', function (socket) {
console.log( socket.client.conn.server.clientsCount + " users connected" );
});
cheers
Also take a look into:
io.sockets.manager.connected
It's a clean list of key value pairs (socket id and connection state?)