Javascript 在什么情况下 AJAX 长/短轮询优于 HTML5 WebSockets?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10028770/
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
In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?
提问by somdow
I am building a small chat application for friends, but unsure about how to get information in a timely manner that is not as manual or as rudimentary as forcing a page refresh.
我正在为朋友构建一个小型聊天应用程序,但不确定如何及时获取信息,这不像强制刷新页面那样手动或基本。
Currently, I am implementing this using simple AJAX, but this has the disadvantage of regularly hitting the server when a short timer elapses.
目前,我正在使用简单的 AJAX 来实现这一点,但这有一个缺点,即在很短的时间过去后会定期访问服务器。
In researching long/short polling, I ran across HTML5 WebSockets. This seemseasy to implement, but I'm not sure if there are some hidden disadvantages. For example, I think WebSockets is only supported by certain browsers. Are there other disadvantages to WebSockets that I should be aware of?
在研究长/短轮询时,我遇到了 HTML5 WebSockets。这似乎很容易实现,但我不确定是否有一些隐藏的缺点。例如,我认为 WebSockets 仅受某些浏览器支持。我应该注意 WebSockets 的其他缺点吗?
Since it seems like both technologies do the same thing, in what sorts of scenarios would one prefer to use one over the other? More specifically, has HTML5 WebSockets made AJAX long/short polling obsolete, or are there compelling reasons to prefer AJAX over WebSockets?
既然这两种技术似乎都在做同样的事情,那么在哪种情况下,人们更喜欢使用一种而不是另一种?更具体地说,是 HTML5 WebSockets 使 AJAX 长/短轮询过时了,还是有令人信服的理由更喜欢 AJAX 而不是 WebSockets?
回答by moka
WebSockets is definitely the future.
WebSockets 绝对是未来。
Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.
长轮询是一种肮脏的解决方法,可以防止像 AJAX 那样为每个请求创建连接——但是当 WebSockets 不存在时会创建长轮询。现在由于 WebSockets,长轮询正在消失。
WebRTC allows for peer-to-peer communication.
WebRTC 允许点对点通信。
I recommend learning WebSockets.
我建议学习WebSockets。
Comparison:
比较:
of different communication techniques on the web
网络上不同的通信技术
AJAX-
request
→response
. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.Long poll-
request
→wait
→response
. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full)| wikipediaWebSockets-
client
↔server
. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good)| wikipediaWebRTC-
peer
↔peer
. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium)| wikipediaServer-Sent Events-
client
←server
. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE)| wikipedia
AJAX-
request
→response
。创建到服务器的连接,发送带有可选数据的请求标头,从服务器获取响应,并关闭连接。 支持所有主要浏览器。长轮询-
request
→wait
→response
。像 AJAX 一样创建一个到服务器的连接,但保持一个保持连接打开一段时间(虽然不长)。在连接过程中,开放的客户端可以从服务器接收数据。由于超时或数据 eof,客户端必须在连接关闭后定期重新连接。在服务器端,它仍然被视为 HTTP 请求,与 AJAX 相同,除了请求的答案将在现在或将来的某个时间发生,由应用程序逻辑定义。 支持图表(完整)| 维基百科WebSockets-
client
↔server
. 创建到服务器的 TCP 连接,并在需要时保持打开状态。服务器或客户端可以轻松关闭连接。客户端通过 HTTP 兼容的握手过程。如果成功,那么服务器和客户端可以随时双向交换数据。如果应用程序需要以两种方式进行频繁的数据交换,则它是有效的。WebSockets 确实有数据帧,包括对从客户端发送到服务器的每条消息进行掩码,因此数据被简单地加密。 支持图表(很好)| 维基百科WebRTC-
peer
↔peer
. 传输在客户端之间建立通信并且与传输无关,因此它可以使用 UDP、TCP 甚至更多抽象层。这通常用于高容量数据传输,例如视频/音频流,其中可靠性是次要的,并且可以牺牲一些帧或质量进展的降低以有利于响应时间,至少,一些数据传输。双方(对等点)可以独立地相互推送数据。虽然它可以完全独立于任何中央服务器使用,但它仍然需要某种方式交换端点数据,在大多数情况下,开发人员仍然使用中央服务器来“链接”对等点。这仅用于交换用于建立连接的基本数据,之后不需要中央服务器。 支撑图(中)| 维基百科服务器发送的事件-
client
←server
。客户端与服务器建立持久和长期的连接。只有服务器可以向客户端发送数据。如果客户端想要向服务器发送数据,则需要使用另一种技术/协议来完成。该协议与 HTTP 兼容且易于在大多数服务器端平台中实现。这是用于代替长轮询的首选协议。支持图表(好,IE除外)| 维基百科
Advantages:
好处:
The main advantage of WebSocketsserver-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.
WebSockets服务器端的主要优点是它不是 HTTP 请求(握手后),而是基于适当消息的通信协议。这使您能够获得巨大的性能和架构优势。例如,在 node.js 中,您可以为不同的套接字连接共享相同的内存,因此它们可以访问共享变量。因此,您不需要使用数据库作为中间的交换点(就像使用 AJAX 或使用 PHP 等语言进行长轮询一样)。您可以将数据存储在 RAM 中,甚至可以直接在套接字之间重新发布。
Security considerations
安全考虑
People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).
人们经常关注 WebSockets 的安全性。现实情况是,它几乎没有什么区别,甚至将 WebSockets 作为更好的选择。首先,使用 AJAX,MITM 的可能性更高,因为每个请求都是一个新的 TCP 连接,它正在穿越互联网基础设施。使用 WebSockets,一旦连接起来,在两者之间进行拦截就更具挑战性,当数据从客户端流式传输到服务器时额外强制执行帧屏蔽以及额外的压缩,这需要更多的努力来探测数据。所有现代协议都支持:HTTP 和 HTTPS(加密)。
P.S.
聚苯乙烯
Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.
请记住,WebSockets 通常有一种非常不同的网络逻辑方法,更像是一直以来的实时游戏,而不是像 http。
回答by bmm6o
One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.
您忽略的一项竞争技术是服务器发送事件/事件源。 什么是长轮询、Websockets、服务器发送事件 (SSE) 和 Comet?对所有这些都有很好的讨论。请记住,其中一些比其他更容易在服务器端集成。
回答by Brant Olsen
For chat applications or any other application that is in constant conversation with the server, WebSockets
are the best option. However, you can only use WebSockets
with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling
to obtain similar functionality.
对于聊天应用程序或与服务器不断对话的任何其他应用程序,是WebSockets
最佳选择。但是,您只能WebSockets
与支持它们的服务器一起使用,因此如果您无法安装所需的库,则可能会限制您使用它们的能力。在这种情况下,您需要使用Long Polling
来获得类似的功能。
回答by JSON C11
XHR pollingA Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.
The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia
Server Sent EventsClient sends request to server. Server sends new data to webpage at any time.
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla
WebSocketsAfter the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.
The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia
XHR 轮询当事件发生时(可能是立即或延迟后)响应请求。需要发出后续请求以接收更多事件。
浏览器向服务器发出异步请求,服务器可能会等待数据可用后再响应。响应可以包含要由客户端执行的编码数据(通常是 XML 或 JSON)或 Javascript。在响应处理结束时,浏览器创建并发送另一个 XHR,以等待下一个事件。因此,浏览器始终与服务器保持一个未完成的请求,以便在每个事件发生时得到响应。维基百科
服务器发送事件客户端向服务器发送请求。服务器随时向网页发送新数据。
传统上,网页必须向服务器发送请求才能接收新数据;即页面向服务器请求数据。通过服务器发送的事件,服务器可以通过将消息推送到网页来随时向网页发送新数据。这些传入的消息可以被视为网页内的事件 + 数据。Mozilla
WebSockets在初始握手之后(通过 HTTP 协议)。使用 WebSocket 协议进行双向通信。
握手以 HTTP 请求/响应开始,允许服务器在同一端口上处理 HTTP 连接以及 WebSocket 连接。一旦建立连接,通信就会切换到不符合 HTTP 协议的双向二进制协议。维基百科