简体   繁体   English

在SocketIO中使用会议室查找用户的状态

[英]Find user presence using rooms in SocketIO

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 由于用户可以打开多个选项卡,因此无法使用on('connect')on('disconnect')在线查找用户

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. 如果为0他处于离线状态。 If its >1 he is online. 如果>1他在线。

But I want to emit an even to admin when he goes online and offline. 但是我想在他上线和下线时向管理员发出一个偶数。 How can I achieve this? 我该如何实现?

In .on('disconnect', ...) when you remove the connection from their room, check the count. 当您从房间.on('disconnect', ...).on('disconnect', ...) ,检查计数。 If the count was 1 before you removed it, then the user is now offline (after you remove them). 如果在删除之前该计数为1,则该用户现在处于脱机状态(在删除它们之后)。

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. 如果他们只是在页面之间导航,则计数将变为零,然后在计时器启动之前返回到1。 Whenever you get a connect event, you clear any timer that is pending for that user. 每当您获得connect事件时,都将清除该用户的所有未决计时器。 To do this, you will have to keep track of the timer on some user-associated object. 为此,您将必须跟踪某个与用户相关的对象上的计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM