如何跟踪我网站用户的在线状态?

发布于 2024-07-26 18:34:49 字数 350 浏览 7 评论 0原文

我想跟踪当前在线的用户。

在线的定义是当他们位于网站的索引页面上时 有聊天功能。

到目前为止,我能想到的就是为用户设置一个 cookie,当下次访问时找到 cookie 时,会进行 ajax 调用来更新表,其中包含用户名、在线状态和时间。

现在我真正的问题是,当他们离开时,我如何可靠地将他们的状态关闭 网站? 我唯一能想到的就是设置没有用户交互的预定时间,然后将状态设置为关闭

但我真正想要的是,只要他们在网站上,无论有或没有交互,都保持状态打开,只有当他们离开网站时才变为关闭

I want to track users that are online at the moment.

The definition of being online is when they are on the index page of the website which
has the chat function.

So far, all I can think of is setting a cookie for the user and, when the cookie is found on the next visit, an ajax call is made to update a table with their username, their status online and the time.

Now my actual question is, how can I reliably turn their status to off when they leave
the website? The only thing I can think of is to set a predetermined amount of time of no user interaction and then set the status to off.

But what I really want is to keep the status on as long as they are on the site, with or without interaction, and only go to off when they leave the site.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

半城柳色半声笛 2024-08-02 18:34:49

完整的解决方案。 从开始到结束。

如果您只想在 index.php 页面上执行此操作,则可以异步向服务器发送更新(AJAX 样式),提醒服务器 $_SESSION["userid"] 仍然在线。

setInterval("update()", 10000); // Update every 10 seconds

function update() {
  $.post("update.php"); // Sends request to update.php
}

您的 update.php 文件将包含一些如下代码:

session_start();
if ($_SESSION["userid"])
  updateUserStatus($_SESSION["userid"]);

这一切都假设您在用户登录您的网站时将您的用户 ID 存储为会话变量。 updateUserStatus() 函数只是一个简单的查询,如下所示:

UPDATE users 
SET lastActiveTime = NOW()
WHERE userid = $userid

这样就可以处理您的存储。 现在检索“在线”用户的列表。 为此,您需要另一个 jQuery 调用和另一个 setInterval() 调用:

setInterval("getList()", 10000) // Get users-online every 10 seconds

function getList() {
  $.post("getList.php", function(list) {
    $("listBox").html(list);
  });
}

该函数每 10 秒从服务器请求一些 HTML。 getList.php 页面将如下所示:

session_start();
if (!$_SESSION["userid"])
  die; // Don't give the list to anybody not logged in

$users = getOnlineUsers(); /* Gets all users with lastActiveTime within the
                              last 1 minute */

$output = "<ul>";
foreach ($users as $user) {
  $output .= "<li>".$user["userName"]."</li>";
}
$output .= "</ul>";

print $output;

这将输出以下 HTML:

<ul>
  <li>Jonathan Sampson</li>
  <li>Paolo Bergantino</li>
  <li>John Skeet</li>
</ul>

该列表包含在名为“list”的 jQuery 变量中。 回头看看我们的最后一个 jQuery 块,您会在那里看到它。

jQuery 将获取此列表,并将其放置在类名为“listBox”的 div 中。

<div class="listBox"></div>

希望这能让你继续前进。

Full Solution. Start-to-finish.

If you only want this working on the index.php page, you could send updates to the server asynchronously (AJAX-style) alerting the server that $_SESSION["userid"] is still online.

setInterval("update()", 10000); // Update every 10 seconds

function update() {
  $.post("update.php"); // Sends request to update.php
}

Your update.php file would have a bit of code like this:

session_start();
if ($_SESSION["userid"])
  updateUserStatus($_SESSION["userid"]);

This all assumes that you store your userid as a session-variable when users login to your website. The updateUserStatus() function is just a simple query, like the following:

UPDATE users 
SET lastActiveTime = NOW()
WHERE userid = $userid

So that takes care of your storage. Now to retrieve the list of users who are "online." For this, you'll want another jQuery-call, and another setInterval() call:

setInterval("getList()", 10000) // Get users-online every 10 seconds

function getList() {
  $.post("getList.php", function(list) {
    $("listBox").html(list);
  });
}

This function requests a bit of HTML form the server every 10 seconds. The getList.php page would look like this:

session_start();
if (!$_SESSION["userid"])
  die; // Don't give the list to anybody not logged in

$users = getOnlineUsers(); /* Gets all users with lastActiveTime within the
                              last 1 minute */

$output = "<ul>";
foreach ($users as $user) {
  $output .= "<li>".$user["userName"]."</li>";
}
$output .= "</ul>";

print $output;

That would output the following HTML:

<ul>
  <li>Jonathan Sampson</li>
  <li>Paolo Bergantino</li>
  <li>John Skeet</li>
</ul>

That list is included in your jQuery variable named "list." Look back up into our last jQuery block and you'll see it there.

jQuery will take this list, and place it within a div having the classname of "listBox."

<div class="listBox"></div>

Hope this gets you going.

手长情犹 2024-08-02 18:34:49

在一般情况下,无法知道用户何时离开您的页面。

但是您可以在幕后做一些事情,以便它们在页面上时经常从您的服务器加载某些内容,例如。 通过加载 以及每分钟重新加载的一些内容:

<meta http-equiv="refresh" content="60">

这将导致一些小的额外服务器负载,但它会执行您想要的操作(如果不是到第二个)。

In the general case, there's no way to know when a user leaves your page.

But you can do things behind the scenes such that they load something from your server frequently while they're on the page, eg. by loading an <iframe> with some content that reloads every minute:

<meta http-equiv="refresh" content="60">

That will cause some small extra server load, but it will do what you want (if not to the second).

蓬勃野心 2024-08-02 18:34:49

那么,聊天功能如何运作呢? 它是一个基于ajax的聊天系统吗?

基于 Ajax 的聊天系统的工作方式是客户端不断地访问聊天服务器以查看队列中是否有新消息。 如果是这种情况,您可以在 cookie 或 PHP 会话中更新用户的在线状态(当然,假设您使用的是 PHP)。 然后您可以将在线超时设置为比更新频率稍长的值。

也就是说,如果您的聊天系统通常每 5 秒向服务器请求一次新消息,那么您可以假设任何在 10-15 秒内未发送请求的用户都不再在聊天页面上。

如果您没有使用基于 ajax 的聊天系统(可能是 Java 或其他系统),那么您仍然可以通过添加定期向服务器发出的 ajax 请求来确定用户是否在线来完成相同的操作。

我不建议将此在线状态信息存储在数据库中。 每隔几秒钟查询一次数据库以查看谁在线、谁不在线,这非常消耗资源,尤其是在大型站点的情况下。 您应该缓存此信息并在缓存(非常快)和数据库(相比之下非常慢)上进行操作。

Well, how does the chat function work? Is it an ajax-based chat system?

Ajax-based chat systems work by the clients consistently hitting the chat server to see if there are any new messages in queue. If this is the case, you can update the user's online status either in a cookie or a PHP Session (assuming you are using PHP, of course). Then you can set the online timeout to be something slightly longer than the update frequency.

That is, if your chat system typically requests new messages from the server every 5 seconds, then you can assume that any user who hasn't sent a request for 10-15 seconds is no longer on the chat page.

If you are not using an ajax-based chat system (maybe Java or something), then you can still accomplish the same thing by adding an ajax request that goes out to the server periodically to establish whether or not the user is online.

I would not suggest storing this online status information in a database. Querying the database every couple of seconds to see who is online and who isn't is very resource intensive, especially if this is a large site. You should cache this information and operate on the cache (very fast) vs. the database (very slow by comparison).

水水月牙 2024-08-02 18:34:49

问题被标记为“jquery” - javascript 解决方案怎么样? 您可以使用 meta/refresh 而不是 window.setInterval(),执行 ajax 请求并提供一些“有用”的东西,例如更新了“谁在线”列表(如果您认为有用;-))

The question is tagged as "jquery" - what about a javascript solution? Instead of meta/refresh you could use window.setInterval(), perform an ajax-request and provide something "useful" like e.g. an updated "who's online" list (if you consider that useful ;-))

葮薆情 2024-08-02 18:34:49

我还没有尝试过这个,所以对此持保留态度:为 window.onunload 设置一个事件处理程序,当用户离开页面时通知服务器。 这样做的一些问题是 1.) 如果浏览器或计算机崩溃,该事件不会触发,2.) 如果用户打开索引页的两个实例并关闭一个,它们将显示为注销,除非您实现引用计数。 就其本身而言,这并不稳健,但与 Jonathan 的轮询方法相结合,应该可以让您拥有相当好的响应时间和更大的更新间隔。

I have not tried this, so take it with a grain of salt: Set an event handler for window.onunload that notifies the server when the user leaves the page. Some problems with this are 1.) the event won't fire if the browser or computer crashes, and 2.) if the user has two instances of the index page open and closes one, they will appear to logout unless you implement reference counting. On its own this is not robust, but combined with Jonathan's polling method, should allow you to have pretty good response time and larger intervals between updates.

我只土不豪 2024-08-02 18:34:49

最终的解决方案是使用 websocket 来实现一些东西。

The ultimate solution would be implementing something with websockets.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文