# 在什么情况下，AJAX长/短轮询优于HTML5 WebSockets？

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. 在研究长/短轮询时，我遇到了HTML5 WebSockets。 This seems easy to implement, but I'm not sure if there are some hidden disadvantages. 似乎很容易实现，但是我不确定是否存在一些隐藏的缺点。 For example, I think WebSockets is only supported by certain browsers. 例如，我认为WebSockets仅受某些浏览器支持。 Are there other disadvantages to WebSockets that I should be aware of? 我应该知道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？

### #2楼

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. 对于聊天应用程序或与服务器进行持续对话的任何其他应用程序， WebSockets是最佳选择。 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. 但是，只能将WebSockets与支持它们的服务器一起使用，因此，如果无法安装所需的库，则可能会限制使用它们的能力。 In which case, you would need to use Long Polling to obtain similar functionality. 在这种情况下，您将需要使用Long Polling来获得类似的功能。

### #3楼

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. 长轮询是一种肮脏的解决方法，可以防止像AJAX一样为每个请求创建连接-但是长轮询是在WebSocket不存在时创建的。 Now due to WebSockets, long polling is going away. 现在由于WebSockets的原因，长时间的轮询将消失。

WebRTC allows for peer-to-peer communication. WebRTC允许对等通信。

I recommend learning WebSockets . 我建议学习WebSockets

# Comparison:比较：

of different communication techniques on the web 网络上不同的通信技术

• AJAX - requestresponse . AJAX- requestresponse 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 - requestwaitresponse . 长轮询 requestwaitresponse Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). 与AJAX一样，创建与服务器的连接，但保持打开状态的连接保持一段时间（虽然时间不长）。 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. 在服务器端，它仍然被视为HTTP请求，与AJAX相同，只是请求的答案将在应用程序逻辑定义的现在或将来的某个时间发生。 support chart (full) | 支持图（完整） | wikipedia 维基百科

• WebSockets - clientserver . WebSockets client server Create a TCP connection to the server, and keep it open as long as needed. 创建与服务器的TCP连接，并根据需要保持打开状态。 The server or client can easily close the connection. 服务器或客户端可以轻松关闭连接。 The client goes through an HTTP compatible handshake process. 客户端经历与HTTP兼容的握手过程。 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. WebSockets确实具有数据框架，其中包括对从客户端发送到服务器的每条消息的屏蔽，因此只需对数据进行加密。 support chart (very good) | 支持图（非常好） | wikipedia 维基百科

• WebRTC - peerpeer . WebRTC peer peer Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. 传输在客户端之间建立通信，并且与传输无关，因此它可以使用UDP，TCP或更多抽象层。 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) | 支持图（中） | wikipedia 维基百科

• Server-Sent Events - clientserver . 服务器发送的事件 - clientserver 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. 该协议是HTTP兼容的，并且在大多数服务器端平台中都易于实现。 This is a preferable protocol to be used instead of Long Polling. 这是代替长轮询使用的首选协议。 support chart (good, except IE) | 支持图（除IE以外，其他都不错） | wikipedia 维基百科

The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. WebSockets服务器端的主要优点是，它不是HTTP请求（握手后），而是基于消息的正确通信协议。 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. 例如，在node.js中，您可以为不同的套接字连接共享相同的内存，因此它们可以访问共享变量。 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). 因此，您不需要在中间使用数据库作为交换点（例如使用AJAX或使用PHP之类的Long Polling）。 You can store data in RAM, or even republish between sockets straight away. 您可以将数据存储在RAM中，甚至可以立即在套接字之间重新发布。

## Security considerations安全注意事项

People are often concerned about the security of WebSockets. 人们经常担心WebSocket的安全性。 The reality is that it makes little difference or even puts WebSockets as better option. 现实情况是，它几乎没有什么不同，甚至使WebSockets成为更好的选择。 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. 首先，使用AJAX， MITM的可能性更高，因为每个请求都是一个遍历Internet基础结构的新TCP连接。 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. 使用WebSockets，一旦连接起来，在两者之间进行拦截就变得更具挑战性，另外，当数据从客户端流向服务器时，还需要强制实施帧屏蔽以及额外的压缩，这需要更多的精力来探查数据。 All modern protocols support both: HTTP and HTTPS (encrypted). 所有现代协议都支持：HTTP和HTTPS（加密）。

## PS聚苯乙烯

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. 请记住，WebSocket通常具有非常不同的网络逻辑方法 ，更像是实时游戏一直都在使用，而不像http。

### #4楼

One contending technology you've omitted is Server-Sent Events / Event Source. 您已省略的一项有争议的技术是服务器发送的事件/事件源。 What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? 什么是长轮询，Websocket，服务器发送事件（SSE）和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. 请记住，其中一些服务器比其他服务器更易于集成。

### #5楼

• XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). XHR轮询当事件发生时（可能是立即发生或延迟），将回答请求。 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. 响应可以包含要由客户端执行的编码数据（通常为XML或JSON）或Javascript。 At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. 在响应处理结束时，浏览器创建并发送另一个XHR，以等待下一个事件。 Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. 因此，浏览器始终保持与服务器的未完成请求，并在每个事件发生时予以答复。 Wikipedia 维基百科

• Server Sent Events Client 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 Mozilla

• WebSockets After the initial handshake (via HTTP protocol). WebSockets初始握手后（通过HTTP协议）。 Communication is done bidirectionally using the WebSocket protocol. 使用WebSocket协议双向进行通信。

The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. 握手始于HTTP请求/响应，允许服务器在同一端口上处理HTTP连接以及WebSocket连接。 Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. 建立连接后，通信将切换到不符合HTTP协议的双向二进制协议。 Wikipedia 维基百科

06-05 1278

12-21 1234
05-09 9272
11-22 122
04-13 1062
01-16 160
04-30 750
08-05 86
10-20 338
09-05 9897
04-30 136
03-20 273