AJAX 轮询频率 - 长轮询还是不长轮询?

发布于 2024-09-25 14:37:38 字数 411 浏览 5 评论 0原文

我正在构建一个需要相对恒定的数据库轮询的网页组件。我可以看到两种不同的方法,我想知道其中一种是否比其他更好,或者我是否缺少第三种选择。

1) 每 1 或 2 秒发送一次 AJAX 请求以检查更新。每次请求无论是否有新数据都会立即返回。
2) 触发单个 AJAX 请求,该请求在收到数据或发生超时之前不会返回。当其中任何一个发生时,它都会触发下一个请求。 (我认为这称为长轮询?)

数据库查询的数量与两者相同,但对于#2,从浏览器发出的请求会更少,这可以节省带宽和客户端资源。对于服务器来说,让一个 PHP 请求保持活动状态并在查询之间休眠,还是每隔几秒启动一次,轮询数据库,然后关闭,哪个更好?还是说没有什么区别,只是我太强调这一点了?

编辑:我想我还应该声明这是一个更大的网络应用程序的聊天小部件。通信中的轻微延迟不会杀死用户,因为聊天是次要功能。

I'm building a component of a web page that needs relatively constant database polling. I can see two different approaches for this, and I'm wondering if one of them is better than the others, or if I'm missing a third option.

1) Send off an AJAX request every 1 or 2 seconds to check for updates. Each request returns immediately whether or not there is new data.
2) Fire off a single AJAX request that will not return until it receives data or a timeout occurs. Upon either of those happening, it fires off the next request. (I think this is called long polling?)

The number of database queries will be the same with either, but with #2 there would be fewer requests firing from the browser which could save bandwidth and client resources. For the server, is it better to have a single PHP request that stays active and sleeps between queries, or that fires up every few seconds, polls the DB, then shuts down? Or is there no difference and I'm stressing about this too much?

EDIT: I suppose I should also state that this is a chat widget of a larger web app. A slight delay in communication is not going to kill a user, as chat is a secondary feature.

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

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

发布评论

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

评论(2

无声静候 2024-10-02 14:37:38

长轮询比轮询具有更好的扩展性(即更少的服务器负载),同时提供更好的响应时间。

如果您的收件人进行轮询,则消息的平均传输时间将是轮询间隔的一半。

通过长轮询,它是即时的 - 服务器仅在无话可说时等待。

如果您要进行聊天消息传递,请进行长轮询;这是一个可用性问题。

长轮询的缺点是实现起来比较复杂。但它并没有那么复杂,并且被广泛实施。因此,如果您无法为您选择的网络服务器使用现成的框架,您可以开始合理地编写一个框架,然后您就会让它工作。

Long polling will scale better (i.e. less server load) than polling, while giving much better response times.

If your recipient polls, the average journey time of a message will be half your poll interval.

With long polling, its instant - the server only waits if there is nothing to say.

If you are doing chat messaging, go long poll; its a usability thing.

The down-side with long polling is it is more complicated to implement; but its not that much more complicated, and it is widely implemented. So if you can't use an off-the-shelf framework for your webserver of choice, you can set about writing one reasonably and you will get it working.

瑾夏年华 2024-10-02 14:37:38

您还可以查看websockets,它是最新浏览器的一部分(或通过Flash 文件 您拖放到页面上)

You can also look at websockets, part of the newest browsers (or emulated via a Flash file you drop on your page)

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