使用EventSource获取用户的在线状态是否可靠? [英] Is it reliable to use EventSource to get User's online status?

查看:82
本文介绍了使用EventSource获取用户的在线状态是否可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了EventSource方法来获取我网站上活跃用户的在线状态。
在此以下JavaScript代码插入每个页面

I have used an EventSource method to get online status of active users on my website. In this following JavaScript code is inserted in every page

var source = new EventSource(set_online.php);

因此,此代码连续执行 set_online.php 文件。

Thus this code is executing set_online.php file continuously.

在服务器端,即 set_online.php 执行代码后

On server side i.e. in set_online.php following code executed

$query = "UPDATE my_db SET last_active = '{$current_time}' WHERE id = {$_SESSION["id"]}";
                $result = mysqli_query($connection, $query);

现在我对此有两个担忧:

Now I have two concerns about this:


  1. 由于数据库实时连续更新last_active,是否会影响服务器负载?

  2. 只要用户在网站上,连接就会打开,是否会创建漏洞?


推荐答案

SSE不适用于此目的 - 或者至少不适用于此目的它。 SSE是从服务器浏览器的事件的恒定流。

SSE is not suitable for this purpose - or at least is not designed for it. SSE is a constant stream of events from server to browser.

但是,您的脚本将起作用。 PHP脚本将做一件事(更新数据库)然后退出。当它退出时,连接关闭。浏览器将看到连接已经死亡,几秒钟后将重新连接。当循环重复时。

Your script will work, though. The PHP script will do one thing (update the database) then exit. When it exits the connection is closed. The browser will see the connection has died, and after a few seconds will reconnect again. When the cycle repeats.

关于你的两个问题:
1.它不是真正连续的,更是每3秒重新连接一次。服务器负载可能很重要。
2.连接未连续打开;但是如果它没有创建任何新的漏洞。

Regarding your two questions: 1. It is not really continuous, more a re-connect every 3 seconds. The server load might be significant. 2. The connection is not open continuously; but if it was it does not create any new vulnerabilities.

我会在JavaScript间隔而不是SSE上使用ajax调用。这些优点:

I would use an ajax call, on a JavaScript interval, instead of SSE. These advantages:


  • 旧技术,更广泛的浏览器支持

  • 显式控制定时器间隔,所以你可以控制延迟和服务器负载之间的平衡。

这篇关于使用EventSource获取用户的在线状态是否可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆