网站通知用什么技术,WebSockets还是轮询?

2021-01-10 11:53 阅读

网站大部分都会用到通知,使用什么技术来实现通知比较好呢?通常有两个选择,一个是轮询,一个是WebSockets。

轮询

轮询很简单,就是每过一段时间(如3分钟)访问一下服务器,看看有没有通知。使用js的setintervalajax可以容易的实现这个功能。实现的简单、成本低、无风险。并不用担心是否增加网站负载,一个在浏览网站的人,每隔三分钟发送一个请求,再正常不过了。

WebSockets

WebSockets是新型技术,可以建立长时间的连接,可以实时响应,可以双向通讯。在某些场合非常有用,适合低延迟、高频率、大数据量的交互。但有技术风险,比如机房防火墙或代理不传递Upgrade头信息,或者会关闭空闲的长连接。

什么时候实用WebSockets

spring文档有一章介绍何时使用WebSockets的问题。大意如下:

WebSockets可以使网页具有动态性和交互性。但是,在许多情况下,结合使用AjaxHTTP streaminglong polling可以提供一种简单有效的解决方案。

例如,新闻,邮件和社交订阅源需要动态更新,但是每几分钟进行一次更新可能是完全可以的。另一方面,协作,游戏和金融应用程序需要更接近实时。

仅延迟并不是决定因素。如果消息量相对较少(例如,监视网络故障),则HTTP流或轮询可以提供有效的解决方案。低延迟,高频率和高容量的结合才是使用WebSocket的最佳案例。

还请记住,在Internet上,不受控制的代理可能会阻止WebSocket交互,这可能是因为未传递Upgrade header,或者是因为它们关闭了长期处于空闲状态的连接。这意味着与面向公众的应用程序相比,将WebSocket用于防火墙内部的应用程序是一个更直接的决定。

When to Use WebSockets

WebSockets can make a web page be dynamic and interactive. However, in many cases, a combination of Ajax and HTTP streaming or long polling can provide a simple and effective solution.

For example, news, mail, and social feeds need to update dynamically, but it may be perfectly okay to do so every few minutes. Collaboration, games, and financial apps, on the other hand, need to be much closer to real-time.

Latency alone is not a deciding factor. If the volume of messages is relatively low (for example, monitoring network failures) HTTP streaming or polling can provide an effective solution. It is the combination of low latency, high frequency, and high volume that make the best case for the use of WebSocket.

Keep in mind also that over the Internet, restrictive proxies that are outside of your control may preclude WebSocket interactions, either because they are not configured to pass on the Upgrade header or because they close long-lived connections that appear idle. This means that the use of WebSocket for internal applications within the firewall is a more straightforward decision than it is for public facing applications.

QQ咨询
电话
微信
微信扫码咨询