0

I'm working on an application where I'd like to show the user the number of users currently online on the site.

For users that are signed in, I have an array of logged in users with their user id. And I'm taking the count to show the number of logged in users. But here is a problem here, I push the user id of a user into the array when the user logs in, and remove it when the user logs off. But if the user doesn't logout and closes the tab, it stays there. But of course, I could do something like, have a table of users signed in, have a last seen column in it and remove the entries if the user was inactive for the last 5 minutes or so. But I wanted to know if there was a better logic to do this.

I tried:

io.on( "connection", function( socket )
{
    console.log( "A user connected" );
    console.log(io.engine.clientsCount);
    console.log(Object.keys(io.sockets.connected).length);
});

But if one user has 10 tabs of my app open, io.engine.clientsCount and Object.keys(io.sockets.connected).length return 10. So what can I do to get the unique number of users online, regardless of how many tabs they have open.

EDIT: I'm using MySQL.

1 Answer 1

2

Each client will create a new socket connection with a unique socket id. I'm not sure its possible to get the total amount of "real" users though.

One way to get closer to it is to store the ip (or a hash of it or whatever) in a list and check if the newly connected client is already connected. But it could be that two "real" users use the page from two different computers in the same network, I.E., they share the public IP.

You could check if there is some way for the client to get something more computer specific from the computer, say a mac address, that way you could determine if its the same computer at least. But it could still be two users sharing the same computer...

This is a hard nut to crack, just like counting "real" unique visitors to a page. And it all comes down to how exact it has to be.
If its not SUPER important to show the exact real users, you could always just show the number of clients and live with a number that could be slightly off.

OR you could force the users to login whenever they want to connect to the socket.io server. That way you could count unique logged in users instead of clients.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.