James Simpson
James Simpson

Reputation: 13718

Keeping track of online/offline status in real-time with NowJS/Node.js?

I've got a site where users login and are connected to NowJS on all pages. I'd like to be able to keep track of their status (online/offline) in near-realtime, but I'm not sure the best way to do this. My initial thought was to just use the connect and disconnect events, but this won't work because those get fired each time the user goes to a new page (since the socket connection is closed while the new page loads).

I've got it somewhat working where I record a timestamp in the database entry for that user on the disconnect event, and then when the connect event fires I check if they've accessed the site within the last 30 seconds. If they haven't, I can assume they are starting a new session. On the disconnect event I use setTimeout to see if they are still online 30 seconds from now, and then set their status to offline if not.

While this mostly works, it seems somewhat hacky and has several edge case issues that could be problematic (not to mention the fact that your going to have a new timeout server-side on each page view). Is there a better way to do this that I'm just overlooking?

Upvotes: 1

Views: 2252

Answers (3)

James Simpson
James Simpson

Reputation: 13718

What I ended up doing was creating a global object that holds the persistent ID for the user (so in this case their ObjectId in MongoDB) as the key and the reference to the setTimeout as the value. I then do clearTimeout on a 'connect' event and delete the key from the object when they are considered offline.

Upvotes: 0

alessioalex
alessioalex

Reputation: 63683

I think the solution here is extending the timeout option for Socket.IO (NowJS uses this internally) or use your hacky solution with setTimeout.

Honestly that seems the best solution considering users can move to another page quickly.

Upvotes: 0

Dan Davies Brackett
Dan Davies Brackett

Reputation: 10081

The right way to do this depends on more than just 'whether there is an open connection'. Are you trying to display to other users whether someone is around/available for chat/whatever? Then you might also consider an inactivity timeout on the page itself (to capture the times when people walk away from their computer without closing the page). If you're doing something else, like metering usage, you might want a different mechanism.

Upvotes: 0

Related Questions