node.js 当 WebSockets 可用时,为什么要使用 AJAX?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10377384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:38:01  来源:igfitidea点击:

Why use AJAX when WebSockets is available?

ajaxnode.jsperformancewebsocket

提问by Hyman

I've been using WebSockets for a while now, I have chosen to create an Agile project management tool for my final year project at University utilizing Node server and WebSockets. I found using WebSockets provided a 624% increase in the number of requests per second my application could process.

我已经使用 WebSockets 一段时间了,我选择使用 Node 服务器和 WebSockets 为大学最后一年的项目创建一个敏捷项目管理工具。我发现使用 WebSockets 使我的应用程序每秒可以处理的请求数量增加了 624%。

However since starting the project I've read of security loopholes, and some browsers choosing to disable WebSockets by default..

但是自从开始这个项目以来,我已经阅读了安全漏洞,并且一些浏览器选择默认禁用 WebSockets..

This leads me to the question:

这让我想到了一个问题:

Why use AJAX when WebSockets seems to do such a great job of lowering latency and resource overhead, is there anything that AJAX does better than WebSockets?

当 WebSockets 似乎在降低延迟和资源开销方面做得如此出色时,为什么要使用 AJAX,AJAX 是否比 WebSockets 做得更好?

回答by kanaka

WebSockets isn't intended to replace AJAX and is not strictly even a replacement for Comet/long-poll (although there are many cases where this makes sense).

WebSockets 并不打算取代 AJAX,甚至严格来说也不是 Comet/long-poll 的替代品(尽管在很多情况下这是有意义的)。

The purpose of WebSockets is to provide a low-latency, bi-directional, full-duplex and long-running connection between a browser and server. WebSockets opens up new application domains to browser applications that were not really possible using HTTP and AJAX (interactive games, dynamic media streams, bridging to existing network protocols, etc).

WebSockets 的目的是在浏览器和服务器之间提供低延迟、双向、全双工和长时间运行的连接。WebSockets 为浏览器应用程序开辟了新的应用程序域,而这些应用程序域使用 HTTP 和 AJAX 是不可能的(交互式游戏、动态媒体流、与现有网络协议的桥接等)。

However, there is certainly an overlap in purpose between WebSockets and AJAX/Comet. For example, when the browser wants to be notified of server events (i.e. push) then Comet techniques and WebSockets are certainly both viable options. If your application needs low-latency push events then this would be a factor in favor of WebSockets. On the other hand, if you need to co-exist with existing frameworks and deployed technologies (OAuth, RESTful APIs, proxies, load balancers) then this would be a factor in favor of Comet techniques (for now).

然而,WebSockets 和 AJAX/Comet 在目的上肯定有重叠。例如,当浏览器想要收到服务器事件的通知(即推送)时,Comet 技术和 WebSockets 当然都是可行的选择。如果您的应用程序需要低延迟推送事件,那么这将是支持 WebSockets 的一个因素。另一方面,如果您需要与现有框架和已部署的技术(OAuth、RESTful API、代理、负载均衡器)共存,那么这将是支持 Comet 技术(目前)的一个因素。

If you don't need the specific benefits that WebSockets provides, then it's probably a better idea to stick with existing techniques like AJAX and Comet because this allows you to re-use and integrate with a huge existing ecosystem of tools, technologies, security mechanisms, knowledge bases (i.e. far more people on stackoverflow know HTTP/Ajax/Comet than WebSockets), etc.

如果您不需要 WebSockets 提供的特定好处,那么坚持使用 AJAX 和 Comet 等现有技术可能是一个更好的主意,因为这允许您重用现有的工具、技术和安全机制的庞大生态系统并与之集成, 知识库(即 stackoverflow 上了解 HTTP/Ajax/Comet 的人比 WebSockets 多得多)等。

On the other hand, if you are creating a new application that just doesn't work well within the latency and connection constraints of HTTP/Ajax/Comet, then consider using WebSockets.

另一方面,如果您要创建的新应用程序在 HTTP/Ajax/Comet 的延迟和连接限制范围内不能很好地工作,那么请考虑使用 WebSockets。

Also, some answers indicate that one of the downsides of WebSockets is limited/mixed server and browser support. Let me just diffuse that a bit. While iOS (iPhone, iPad) still supports the older protocol (Hixie) most WebSockets servers support both Hixie and the HyBi/IETF 6455version. Most other platforms (if they don't already have built-in support) can get WebSockets support via web-socket-js(Flash based polyfill). This covers the vast majority of web users. Also, if you are using Node for the server backend, then consider using Socket.IOwhich includes web-socket-js as a fallback and if even that is not available (or disabled) then it will fall back to using whatever Comet technique is available for the given browser.

此外,一些答案表明 WebSockets 的缺点之一是服务器和浏览器支持有限/混合。让我稍微扩散一下。虽然 iOS(iPhone、iPad)仍然支持旧协议(Hixie),但大多数 WebSockets 服务器同时支持 Hixie 和 HyBi/ IETF 6455版本。大多数其他平台(如果它们还没有内置支持)可以通过web-socket-js(基于 Flash 的 polyfill)获得 WebSockets 支持。这涵盖了绝大多数网络用户。此外,如果您使用 Node 作为服务器后端,那么请考虑使用Socket.IO,其中包括 web-socket-js 作为后备,如果甚至不可用(或禁用),那么它将回退到使用任何 Comet 技术可用于给定的浏览器。

Update: iOS 6 now supports the current HyBi/IETF 6455 standard.

更新:iOS 6 现在支持当前的 HyBi/IETF 6455 标准。

回答by Myst

Fast forward to December 2017, Websockets are supported by (practically) every browserand their use is very common.

快进到 2017 年 12 月,(实际上)每个浏览器都支持 Websocket,并且它们的使用非常普遍。

However, this does not mean that Websockets managed to replace AJAX, at least not completely, especially as HTTP/2 adaptation is on the rise.

然而,这并不意味着 Websockets 成功取代了 AJAX,至少不是完全取代了 AJAX,尤其是在 HTTP/2 适配正在兴起的情况下。

The short answer is that AJAX is still great for most REST applications, even when using Websockets. But god is in the details, so...:

简短的回答是 AJAX 仍然适用于大多数 REST 应用程序,即使在使用 Websockets 时也是如此。但上帝在细节中,所以...:

AJAX for polling?

用于投票的 AJAX?

The use of AJAX for polling (or long polling) is dying out(and it should be), but it still remains in use for two good reasons (mainly for smaller web apps):

使用 AJAX 进行轮询(或长轮询)正在消亡(它应该如此),但它仍然在使用有两个很好的原因(主要用于较小的 Web 应用程序):

  1. For many developers, AJAX is easier to code, especially when it comes to coding and designing the backend.

  2. With HTTP/2, the highest cost related to AJAX (the establishment of a new connection) was eliminated, allowing AJAX calls to be quite performant, especially for posting and uploading data.

  1. 对于许多开发人员来说,AJAX 更容易编码,尤其是在编码和设计后端时。

  2. 使用 HTTP/2,消除了与 AJAX(建立新连接)相关的最高成本,使 AJAX 调用非常高效,尤其是在发布和上传数据方面。

However, Websocket push is far superior to AJAX(no need to re-authenticate or resend headers, no need for "no data" roundtrips, etc'). This was discusseda number of times.

但是,Websocket 推送远优于 AJAX(无需重新验证或重新发送标头,无需“无数据”往返等)。这个问题讨论了很多次。

AJAX for REST?

用于 REST 的 AJAX?

A better use for AJAX is REST API calls. This use simplifies the code base and prevents the Websocket connection from blocking (especially on medium sized data uploads).

AJAX 的更好用途是 REST API 调用。这种使用简化了代码库并防止 Websocket 连接阻塞(尤其是在中型数据上传时)。

There are a number of compelling reasons to prefer AJAX for REST API callsand data uploads:

REST API 调用和数据上传中更喜欢 AJAX有很多令人信服的理由

  1. The AJAX API was practically designed for REST API calls and it's a great fit.

  2. REST calls and uploads using AJAX are significantly easier to code, both on the client and the backend.

  3. As data payload increases, Websocket connections might get blocked unless message fragmentation / multiplexing logic is coded.

    If an upload is performed in a single Websocket sendcall, it could block a Websocket stream until the upload had finished. This will reduce performance, especially on slower clients.

  1. AJAX API 实际上是为 REST API 调用而设计的,非常适合。

  2. 使用 AJAX 的 REST 调用和上传在客户端和后端都更容易编码。

  3. 随着数据负载的增加,除非对消息碎片/多路复用逻辑进行编码,否则 Websocket 连接可能会被阻止。

    如果在单个 Websocketsend调用中执行上传,则可能会阻塞 Websocket 流,直到上传完成。这会降低性能,尤其是在速度较慢的客户端上。

A common design uses small bidi messages transferred over Websockets while REST and data uploads (client to server) leverage AJAX's ease of use to prevent the Websocket from blocking.

一个常见的设计使用通过 Websocket 传输的小型双向消息,而 REST 和数据上传(客户端到服务器)利用 AJAX 的易用性来防止 Websocket 阻塞。

However, on larger projects, the flexibility offered by Websockets and the balance between code complexity and resource management will tip the balance in favor of Websockets.

然而,在较大的项目中,Websockets 提供的灵活性以及代码复杂性和资源管理之间的平衡将使平衡偏向于 Websockets。

For example, Websocket based uploads could offer the ability to resume large uploads after a connection is dropped and re-established (remember that 5GB movie you wanted to upload?).

例如,基于 Websocket 的上传可以提供在连接断开和重新建立后恢复大上传的能力(还记得你想上传的 5GB 电影吗?)。

By coding upload fragmentation logic, it's easy to resume an interrupted upload (the hard part was coding the thing).

通过编码上传碎片逻辑,很容易恢复中断的上传(困难的部分是编码)。

What about HTTP/2 push?

HTTP/2 推送怎么样?

I should probably add that the HTTP/2 push feature doesn't (and probably can't) replace Websockets.

我可能应该补充一点,HTTP/2 推送功能不会(也可能不能)取代 Websocket。

This had been discussed herebefore, but suffice to mention that a single HTTP/2 connection serves the whole browser (all the tabs/windows), so data being pushed by HTTP/2 doesn't know which tab/window it belongs to, eliminating it's capacity to replace Websocket's ability to push data directly to a specific browser tab / window.

之前已经讨论过,但值得一提的是,单个 HTTP/2 连接服务于整个浏览器(所有选项卡/窗口),因此 HTTP/2 推送的数据不知道它属于哪个选项卡/窗口,消除它取代 Websocket 将数据直接推送到特定浏览器选项卡/窗口的能力的能力。

While Websockets are great for small bi-directional data communication, AJAX still carried a number of advantages - especially when considering larger payloads (uploads etc').

虽然 Websockets 非常适合小型双向数据通信,但 AJAX 仍然具有许多优势 - 特别是在考虑更大的有效负载(上传等)时。

And Security?

和安全?

Well, generally, the more trust and control is offered to a programmer, the more powerful the tool... and the more security concerns that creep up.

嗯,一般来说,提供给程序员的信任和控制越多,工具就越强大……并且出现的安全问题也就越多。

AJAX by nature would have the upper hand, since it's security is built in to the browser's code (which is sometimes questionable, but it's still there).

AJAX 本质上会占上风,因为它的安全性内置于浏览器的代码中(这有时是有问题的,但它仍然存在)。

On the other hand, AJAX calls are more susceptible to "man in the middle" attacks, while Websockets security issues are usually bugs in the application code that introduced a security flaw (usually backend authentication logic is where you'll find these).

另一方面,AJAX 调用更容易受到“中间人”攻击,而 Websockets 安全问题通常是引入安全漏洞的应用程序代码中的错误(通常后端身份验证逻辑是您可以找到这些的地方)。

Personally I don't find this to be that big of a difference, if anything I think Websockets are slightly better off, especially when you know what you're doing.

就我个人而言,我认为这没有那么大的区别,如果有的话,我认为 Websockets 稍微好一些,尤其是当您知道自己在做什么时。

My Humble Opinion

我的拙见

IMHO, I would use Websockets for everything but REST API calls. Big data uploads I would fragment and send over Websockets when possible.

恕我直言,除了 REST API 调用之外,我会使用 Websockets 来处理所有事情。大数据上传我会尽可能分段并通过 Websockets 发送。

Polling, IMHO, should be outlawed, the cost in network traffic is horrid and Websocket push is easy enough to manage even for new developers.

轮询,恕我直言,应该被取缔,网络流量的成本是可怕的,即使对于新开发人员来说,Websocket 推送也很容易管理。

回答by Alessandro Alinone

In addition to issues with older browsers (including IE9, as WebSockets will be supported starting from IE10), there are still big problems with network intermediaries not yet supporting WebSockets, including transparent proxies, reverse proxies, and load balancers. There are some mobile carriers that completely block the WebSocket traffic (that is, after the HTTP UPGRADE command).

除了旧浏览器(包括 IE9,因为将从 IE10 开始支持 WebSockets)的问题之外,还存在不支持 WebSockets 的网络中介的大问题,包括透明代理、反向代理和负载均衡器。有一些移动运营商完全阻止了 WebSocket 流量(即在 HTTP UPGRADE 命令之后)。

With years passing, WebSockets will be more and more supported, but in the meantime you should always have an HTTP-based fall-back method for sending data to the browsers.

随着时间的流逝,WebSockets 将得到越来越多的支持,但与此同时,您应该始终拥有一种基于 HTTP 的回退方法来将数据发送到浏览器。

回答by Tim Lovell-Smith

Most of the complaining I have read about websockets and security is from security vendors of web browser security and firewall security tools. The problem is they don't know how to do security analysis of websockets traffic, because once it has done the upgrade from HTTP to the websocket binary protocol, the packet content and its meaning is application specific (based on whatever you program). This is obviously a logistic nightmare for these companies whose livelihood is based on analyzing and classifying all your internet traffic. :)

我读到的关于 websockets 和安全性的大部分抱怨来自 Web 浏览器安全性和防火墙安全工具的安全供应商。问题是他们不知道如何对 websockets 流量进行安全分析,因为一旦它完成了从 HTTP 到 websocket 二进制协议的升级,数据包的内容及其含义是特定于应用程序的(基于你编程的任何内容)。对于这些以分析和分类所有互联网流量为生的公司来说,这显然是一场后勤噩梦。:)

回答by jli

WebSockets don't work in older web browsers, and the ones that do support itoften have differing implementations. That's pretty much the only good reason why they aren't used all the time in place of AJAX.

WebSockets 在旧的 Web 浏览器中不起作用,支持它的浏览器通常有不同的实现。这几乎是不一直使用它们代替 AJAX 的唯一原因。

回答by Gaurav Gandhi

I don't think we can do a a clear comparison of Websockets and HTTP as they're no rivals nor solve the same problems.

我不认为我们可以对 Websockets 和 HTTP 做一个明确的比较,因为它们不是竞争对手,也不能解决相同的问题。

Websockets are a great choice for handling long-lived bidirectional data streaming in near real-time manner, whereas REST is great for occasional communications. Using websockets is a considerable investment, hence it is an overkill for occasional connections.

Websockets 是以近乎实时的方式处理长期双向数据流的绝佳选择,而 REST 非常适合偶尔的通信。使用 websockets 是一项相当大的投资,因此对于偶尔的连接来说是一种矫枉过正。

You may find that Websockets do better when high loads are present, HTTP is slightly faster in some cases because it can utilise caching. Comparing REST with Websockets is like comparing apples to oranges.

您可能会发现 Websocket 在存在高负载时表现更好,在某些情况下 HTTP 稍微快一点,因为它可以利用缓存。将 REST 与 Websockets 进行比较就像将苹果与橙子进行比较。

We should be checking which one provides better solution for our application, which one fits best in our use case wins.

我们应该检查哪一个为我们的应用程序提供了更好的解决方案,哪一个最适合我们的用例。

回答by Mike D

An example of the differences between HTTP and Websockets in the form of a client-size lib that can handle Websocket endpoint like REST APIs and RESTful endpoints like Websockets on the client. https://github.com/mikedeshazer/sockrestAlso, for those who are trying to consume a websocket API on client or vice versa the way they are used to. The libs/sockrest.js pretty much makes it clear the differences (or rather is supposed to).

HTTP 和 Websockets 之间差异的示例,以客户端大小的 lib 形式表示,该库可以处理客户端上的 Websocket 端点(如 REST API)和 RESTful 端点(如 Websockets)。 https://github.com/mikedeshazer/sockrest另外,对于那些试图在客户端上使用 websocket API 的人,反之亦然。libs/sockrest.js 几乎清楚地说明了差异(或者更确切地说是应该)。