简体   繁体   English

如何查找在线用户

[英]How to find the users who are online

I was making a chat for my website. 我正在为我的网站聊天。 For that I need to find how many registered users are online. 为此,我需要查找有多少注册用户在线。 I count the number of sessions and store them in a table. 我计算会话数并将其存储在表中。 When they logout, their name is removed from that table. 当他们注销时,其名称将从该表中删除。 Now if they don't click logout and directly close their tab, it does not make them go offline. 现在,如果他们不单击注销并直接关闭其选项卡,则不会使他们脱机。 Their name still exists in table. 它们的名称仍存在于表中。 So to remove them, I found a very complicated algorithm online. 因此,要删除它们,我在线上找到了一个非常复杂的算法。 It empties that table in every five minutes and then again add the names of the people who are online. 它每五分钟清空该表一次,然后再次添加在线用户的姓名。 But the problem is that while this happens, the chat is interrupted. 但是问题是,尽管发生这种情况,但聊天中断了。 So I need a way out for this problem 所以我需要一个解决这个问题的方法

Add a column for "last active." 为“上次活动”添加一列。 Every time the user performs some action (which may include the browser polling for more messages via AJAX, for example) you update that column to NOW() . 每次用户执行某些操作(例如,可能包括浏览器通过AJAX轮询更多消息)时,您都将该列更新为NOW() Then your query for finding active users can be something like: 然后,用于查找活动用户的查询可以是:

SELECT user.name FROM user
    WHERE DATE_ADD(user.last_active, INTERVAL 5 MINUTE) >= NOW();

Deleting old records from the table is fine, but is probably an optional enhancement (depending on site load). 从表中删除旧记录是可以的,但可能是可选的增强功能(取决于站点负载)。

Maybe look into this: destroy session on window close? 也许调查一下: 销毁窗口关闭会话?

Instead of destroying the session you could execute a query that deletes the row. 您可以执行删除该行的查询,而不是破坏会话。

I think there are 2 solution. 我认为有2个解决方案。

1.) Save a timestamp and make a cronjob. 1.)保存时间戳记并进行cronjob。 The cron check every minute or 2 minuten how old the entries are and delete entries older then 5 minutes for example. cron每分钟或每2分钟检查一次条目的年龄,例如删除5分钟之前的条目。

2.) Second way make a funktion which do the same as Point 1 but run the function on every page call. 2)第二种方法进行的功能与第1点相同,但在每次页面调用时都运行该函数。 But this is not really efficiant and make a lot of load. 但这并不是真正有效的方法,会带来很多负担。

如果您将会话存储在db表中,则可以轻松检查活动的会话,请查看php手册http://in.php.net/manual/en/function.session-set-save-handler.php

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

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