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.
到目前为止,我能想到的只是为用户设置一个cookie,当下次访问时找到cookie时,会调用ajax来更新一个表,其中包含用户名,在线状态和时间。
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.
但我真正想要的是,只要他们在网站上,无论是否有互动,都要保持状态,只有在他们离开网站时才会关闭。
6 个解决方案
#1
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.
如果您只想在index.php页面上使用它,则可以异步(AJAX样式)向服务器发送更新,以警告服务器$ _SESSION [“userid”]仍在线。
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:
你的update.php文件会有一些像这样的代码:
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:
这一切都假定您在用户登录您的网站时将您的用户ID存储为会话变量。 updateUserStatus()函数只是一个简单的查询,如下所示:
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:
这样可以处理您的存储空间。现在检索“在线”用户列表。为此,您需要另一个jQuery调用,以及另一个setInterval()调用:
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:
此函数每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;
That would output the following HTML:
那将输出以下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.
该列表包含在名为“list”的jQuery变量中。回顾我们上一个jQuery块,你会在那里看到它。
jQuery will take this list, and place it within a div having the classname of "listBox."
jQuery将获取此列表,并将其放在类名为“listBox”的div中。
<div class="listBox"></div>
Hope this gets you going.
希望这能让你前进。
#2
The ultimate solution would be implementing something with websockets.
最终的解决方案是使用websockets实现一些东西。
#3
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).
这将导致一些额外的服务器负载,但它会做你想要的(如果没有到第二个)。
#4
Well, how does the chat function work? Is it an ajax-based chat system?
那么,聊天功能如何运作?它是一个基于ajax的聊天系统吗?
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.
基于Ajax的聊天系统由客户端工作,不断地访问聊天服务器以查看队列中是否有任何新消息。如果是这种情况,您可以在cookie或PHP会话中更新用户的在线状态(当然,假设您使用的是PHP)。然后,您可以将在线超时设置为略长于更新频率的内容。
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.
也就是说,如果您的聊天系统通常每5秒钟从服务器请求新消息,那么您可以假设任何未发送10-15秒请求的用户不再在聊天页面上。
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.
如果您没有使用基于ajax的聊天系统(可能是Java或其他东西),那么您仍然可以通过添加一个定期发送到服务器的ajax请求来确定用户是否在线,从而完成同样的事情。
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).
我不建议将此在线状态信息存储在数据库中。每隔几秒查询数据库以查看谁在线以及谁不在线是非常耗费资源的,特别是如果这是一个大型站点。您应该缓存此信息并在缓存(非常快)和数据库上运行(相比之下非常慢)。
#5
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 ;-))
问题被标记为“jquery” - javascript解决方案怎么样?您可以使用window.setInterval()代替元/刷新,执行ajax请求并提供“有用”的内容,例如:更新的“谁在线”列表(如果您认为有用;-))
#6
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.
我没有尝试过这个,所以请耐心等待:为window.onunload设置一个事件处理程序,当用户离开页面时通知服务器。这方面的一些问题是1.)如果浏览器或计算机崩溃,事件将不会触发,并且2.)如果用户有两个索引页面打开并关闭一个实例,除非您实现引用计数,否则它们将显示为注销。它本身并不强大,但结合Jonathan的轮询方法,应该可以让你有更好的响应时间和更新之间更大的间隔。
#1
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.
如果您只想在index.php页面上使用它,则可以异步(AJAX样式)向服务器发送更新,以警告服务器$ _SESSION [“userid”]仍在线。
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:
你的update.php文件会有一些像这样的代码:
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:
这一切都假定您在用户登录您的网站时将您的用户ID存储为会话变量。 updateUserStatus()函数只是一个简单的查询,如下所示:
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:
这样可以处理您的存储空间。现在检索“在线”用户列表。为此,您需要另一个jQuery调用,以及另一个setInterval()调用:
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:
此函数每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;
That would output the following HTML:
那将输出以下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.
该列表包含在名为“list”的jQuery变量中。回顾我们上一个jQuery块,你会在那里看到它。
jQuery will take this list, and place it within a div having the classname of "listBox."
jQuery将获取此列表,并将其放在类名为“listBox”的div中。
<div class="listBox"></div>
Hope this gets you going.
希望这能让你前进。
#2
The ultimate solution would be implementing something with websockets.
最终的解决方案是使用websockets实现一些东西。
#3
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).
这将导致一些额外的服务器负载,但它会做你想要的(如果没有到第二个)。
#4
Well, how does the chat function work? Is it an ajax-based chat system?
那么,聊天功能如何运作?它是一个基于ajax的聊天系统吗?
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.
基于Ajax的聊天系统由客户端工作,不断地访问聊天服务器以查看队列中是否有任何新消息。如果是这种情况,您可以在cookie或PHP会话中更新用户的在线状态(当然,假设您使用的是PHP)。然后,您可以将在线超时设置为略长于更新频率的内容。
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.
也就是说,如果您的聊天系统通常每5秒钟从服务器请求新消息,那么您可以假设任何未发送10-15秒请求的用户不再在聊天页面上。
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.
如果您没有使用基于ajax的聊天系统(可能是Java或其他东西),那么您仍然可以通过添加一个定期发送到服务器的ajax请求来确定用户是否在线,从而完成同样的事情。
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).
我不建议将此在线状态信息存储在数据库中。每隔几秒查询数据库以查看谁在线以及谁不在线是非常耗费资源的,特别是如果这是一个大型站点。您应该缓存此信息并在缓存(非常快)和数据库上运行(相比之下非常慢)。
#5
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 ;-))
问题被标记为“jquery” - javascript解决方案怎么样?您可以使用window.setInterval()代替元/刷新,执行ajax请求并提供“有用”的内容,例如:更新的“谁在线”列表(如果您认为有用;-))
#6
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.
我没有尝试过这个,所以请耐心等待:为window.onunload设置一个事件处理程序,当用户离开页面时通知服务器。这方面的一些问题是1.)如果浏览器或计算机崩溃,事件将不会触发,并且2.)如果用户有两个索引页面打开并关闭一个实例,除非您实现引用计数,否则它们将显示为注销。它本身并不强大,但结合Jonathan的轮询方法,应该可以让你有更好的响应时间和更新之间更大的间隔。