什么是长轮询的利弊与定期轮询?利弊、长轮询

2023-09-10 19:23:14 作者:左眸°

我有我需要检查服务器的更新每一秒的网页。更新可能会比较频繁或不频繁。可能有很多的Web客户端同时检查服务器进行更新。这可以是一个AJAX请求每秒,或长轮询的模拟服务器推送。哪种方法我想使用,为什么?这似乎是启动HTTP连接每一秒钟可能使长轮询方法preferable的开销。另一方面,有可能是一个限制到可以由服务器维护的并发连接的数量。这些技术的一些比较将是有益的我来决定哪个方向走。

I have a web page that I need to check the server for an update every second. Updates could be relatively frequent or infrequent. There could be a lot of web clients simultaneously checking the server for updates. This could either be an AJAX request every second, or a "long poll" which emulates server push. Which method would I want to use and why? It seems like the overhead of initiating an HTTP connection every second might make the long polling method preferable. On the other hand, there is probably a limit to the number of concurrent connections that can be maintained by the server. Some comparisons of these techniques would be useful for me to decide which way to go.

推荐答案

这取决于你的网络服务器。有新的Web服务器正在开发的理解AJAX /彗星的风格,使长轮询非常有效的。请参见 Mongrel2 一个例子。

It depends on your webserver. There are newer webservers being developed that understand AJAX/Comet style and make long-polling very efficient. See Mongrel2 for an example.

您也可以考虑定期轮询,但使其动态。不知道你的域名,我无法作出具体的建议。但是想象一下,在一个聊天应用程序。每一秒的轮询相反,我可能会等待一段后,聊天消息发送给其他人的时间。然后检查多一点经常一会儿,如果我依然什么也没得到,慢下来(因为其他人可能会消失)。我可能会投票的时间间隔从1秒到30秒,这取决于具体情况。

You might also consider regular polling, but making it dynamic. Not knowing your domain, I can't make a specific recommendation. But imagine in a chat application. Instead of polling every second, I might wait a little after a chat message is sent to give the other person time. Then check a little more frequently for a while, and if I still get nothing, slow down (as the other person might be gone). I might have poll intervals from 1 second to 30 seconds depending on the situation.

这将所有需要的感觉进行测试,但平均而言,我也许可以让它觉得自己要秒钟的轮询,当平均它更像是20。

It would all need to be tested for feel, but on average, I might be able to make it feel like 1 second polling, when on average it's more like 20.