长轮询与常规轮询相比有何优缺点?
我有一个网页,我需要每秒检查服务器是否有更新。更新可能相对频繁或不频繁。可能有很多 Web 客户端同时检查服务器是否有更新。这可以是每秒一次的 AJAX 请求,也可以是模拟服务器推送的“长轮询”。我想使用哪种方法?为什么?似乎每秒启动一个 HTTP 连接的开销可能会使长轮询方法更可取。另一方面,服务器可以维护的并发连接数可能是有限的。对这些技术进行一些比较有助于我决定走哪条路。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您的网络服务器。正在开发新的网络服务器,它们能够理解 AJAX/Comet 风格,并使长轮询变得非常高效。有关示例,请参阅 Mongrel2。
您也可以考虑定期轮询,但使其动态化。由于不了解您的域名,我无法提出具体建议。但想象一下在聊天应用程序中。我可能会在发送聊天消息后稍等一下,以便给对方时间,而不是每秒轮询。然后稍微频繁地检查一段时间,如果我仍然什么也没得到,就放慢速度(因为另一个人可能已经走了)。根据具体情况,我的轮询间隔可能为 1 秒到 30 秒。
这一切都需要进行感觉测试,但平均而言,我可能能够让它感觉像 1 秒轮询,而平均而言它更像是 20 秒。
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.
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.
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.