Reputation: 11780
I'm trying to emit an event when a user goes online and offline. Since a user can open multiple tabs, finding user online using on('connect')
and on('disconnect')
won't work
Instead, every time a user joins I create a room for each user and joins them. To check user is online just count the no. of clients that room. If it's 0
he is offline. If its >1
he is online.
But I want to emit an even to admin when he goes online and offline. How can I achieve this?
Upvotes: 1
Views: 716
Reputation: 707158
In .on('disconnect', ...)
when you remove the connection from their room, check the count. If the count was 1 before you removed it, then the user is now offline (after you remove them).
If you have multiple pages in your app or your user may hit refresh, then you also have to allow for momentary disconnects followed by a connect. In that case, when you detect the room count has gone to zero, you set a timer for some small amount of time and check again. If the count is still zero when the timer fires, you can then consider them offline.
If they were just navigating between pages, the count will go to zero, then back to one before the timer fires. Whenever you get a connect
event, you clear any timer that is pending for that user. To do this, you will have to keep track of the timer on some user-associated object.
Upvotes: 4