How do I find out how many connected clients there are to a HTTP Server in Node.js?

Let's say I'm running an app, that uses Express and Socket.io both listening on the same instance of a Node http.Server.

Every second I want to log to the console the total number of connected clients (either HTTP or WS) for monitoring purposes.

setInterval(logConnectedClientInfo, 1000);

How can I implement the method logConnectedClientInfo()?


I know I could just do this by execing lsof but I'm interested if there's a way to do it in Node?

will this work ?

server.on('connection', function (socket) {
    activeConnections++;

    socket.on('end', function() {
        activeConnections--;
    });

});

I found the answer. The net module has a method on a server called server.getConnections(). A http.Server in Node (0.10.30) inherits from net.Server. See lib/_http_server.js in node core:

util.inherits(Server, net.Server);

So my method would look like:

function logConnectedClientInfo() {
    server.getConnections(function(err, count){
        if(err) throw err;
        console.log(count);
    });
}