Ackados Ackados - 3 years ago 306
Node.js Question

Count number of online users with nodeJS and without duplicates

I'm having trouble displaying the correct amount of online users. A question similar to this have shown me that I can count the users this way:

var count = 0
socket.on('connection', function(client) {
client.on('disconnect', function(){

The issue I'm constantly running into with that method is that when a user happens to reload the page too quickly, the counter pulls in too much it can throw out.

enter image description here

As you can see, on the right side of the image, a user spammed the reload and it caught more users online than there actually is. (There was only one user on the server at this time)

My question is is there a better or more reliable way to count the exact amount users online without the extra 'virtual users', without using the

Answer Source

If they're logging in as a user, then you should authenticate them to the socket. Use that authentication to see if they already have a session, and disconnect them decrementing the count, before you increment it again with the new session.

An example below. The clients objects stores the connected clients, with values being the sockets they're connected to.

var clients = {};
socket.on('connection', function(client) {
  //Authenticate the client (Using query string parameters, auth tokens, etc...), and return the userID if the user.
  var userId = authenticate(client);

  if ( !userId ) {
    //Bad authentication, disconnect them

  if (clients[userId]) {
    //They already have a session, disconnect
    //Set updated session here
    clients[userId] = client;
  client.broadcast({count: Object.keys(clients).length})
  client.on('disconnect', function(){
    delete clients[userId];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download