💨 Author: Laker, because he likes LOL god Faker and is a fan of NBA Lakers 🏀 (Laker) (mainly a fan of Lao James). His surname is Li, so he takes the pen name laker ❤️. Laker ❤️ likes to share his problems and solutions in his work, as well as some reading notes and experiences. 🌰 I created a wechat public account [Java Factory Interviewer] for communication and sharing with everyone 🏰 personal wechat [Lakernote], with the author’s note under the code: CV way.
The article directories
-
- What is the difference between long polling, WebSocket and server sending events?
- Ajax polling protocol
- HTTP long polling protocol
- Web sockets agreement
- Server sends Event protocols (SSEs)
- conclusion
-
- SSEs Protocol analysis
- The client DEMO
- The service side DEMO
What is the difference between long polling, WebSocket and server sending events?
Long polling, WebSocket, and server sending events are popular communication protocols between clients and servers such as Web browsers and Web servers. First, let’s look at standard HTTP Web requests. The following is a sequence of events for a regular HTTP request:
- The client opens the connection and requests data from the server.
- The server calculates the response.
- The server sends the response back to the client based on the opened request.
Ajax polling protocol
Polling is a standard technique used by most AJAX applications. The basic idea is that the client repeatedly polls (or requests) the server for data. The client issues a request and waits for the server to respond with data. If no data is available, an empty response is returned.
- The client uses regular HTTP to open the connection and request data from the server.
- The requested web page sends the request to the server at a fixed interval (for example, 0.5 seconds).
- The server calculates the response and sends it back, just like regular HTTP traffic.
- The client periodically repeats the above three steps to get updates from the server.
The problem with polling is that the client must constantly ask the server for any new data. Many empty responses are generated, resulting in HTTP overhead.
HTTP long polling protocol
This is a variation of the traditional polling technique, which allows the server to push information to the client as data becomes available. With long-polling, the client can request information from the server as normal Polling, but the server may not respond immediately. That’s why this technique is sometimes called a “pending request.”
- If the server does not have any data available to the client, the server holds the request and waits until some data is available, rather than sending an empty response.
- Once the data is available, the complete response is sent to the client. The client then immediately rerequests the information from the server so that the server almost always has an available wait request that the server can use to respond to events.
The basic lifecycle of an application that uses HTTP long-polling is as follows:
- The client makes the initial request using regular HTTP and then waits for the response.
- The server delays its response until updates are available or a timeout occurs.
- When an update is available, the server sends the complete response to the client.
- Clients typically send a new long poll request as soon as they receive the response, or after a pause in the allowed wait time.
- Each long poll request has a timeout. After a connection is closed due to a timeout, the client must reconnect periodically.
Web sockets agreement
WebSocket provides full-duplex communication channels over a single TCP connection. It provides a persistent connection between the client and server that both sides can use to start sending data at any time. The client establishes a WebSocket connection through a process called a WebSocket handshake. If this process is successful, the server and client can exchange data in both directions at any time. The WebSocket protocol makes the communication between the client and the server have lower overhead, thus promoting the real-time data transmission between the server and the client. By providing a standardized way for the server to send content to the browser without being asked by the client, and allowing messages to be passed back while keeping the connection open.
Server sends Event protocols (SSEs)
Under the SSEs, clients establish persistent, long-term connections to servers. The server uses this connection to send data to the client. If the client wants to send data to the server, another technology/protocol needs to be used.
- The client requests data from the server using regular HTTP.
- The requested web page opens a connection to the server.
- As soon as new information becomes available, the server sends the data to the client.
SSEs are best when we need live traffic from the server to the client, or when the server is generating data in a loop and will send multiple events to the client.
conclusion
Common front-end and back-end message communication protocols are as follows:
- Traditional polling protocol
- Http long polling protocol
- Web sockets agreement
- SSEs agreement
SSEs Protocol analysis
The other methods are already familiar, except for the SSEs protocol, so what are SSEs?
SSE, server-sent Events, also known as EventSource, is a server-side event pushing technology that has been written into THE HTML 5 standard. It allows a one-way channel to be established between the client and the Server so that the Server can continuously push event messages to the client in one direction. SSE is suitable for scenarios where data does not need to be sent from the client, but is updated by certain server operations, such as stock quotes, shared facility updates, friend status updates, etc.
The general process has been introduced above. To put it simply, SSE means that the browser sends an HTTP request to the server, and then the server continuously pushes “message” to the browser in one direction. The format of the message is simple: “information” is prefixed with “data:” and then ended with “\n\n”.
SSE is similar to WebSocket in that it is used to establish a communication channel between the browser and the server.
The comparison is as follows:
SSE | Websocket |
---|---|
The HTTP protocol can run directly on existing proxy servers and authentication technologies | Independent Websocket protocol that requires server-side support |
SSE is a one-way channel and can only be sent from the server to the browser. | Full duplex channel, two-way communication, more powerful |
Lightweight and easy to implement | Relatively complex implementation |
Reconnection is supported by default | You need to disconnect and reconnect yourself |
Text transmission | Binary transmission |
Supports user-defined message types to be sent | – |
The client DEMO
<script type="text/javascript">
if(!!!!!window.EventSource) {
var source = new EventSource('push');
// Open the connection
source.addEventListener('open'.function (evt) {
// console.info(" Connection is already open ");
}, false);
// Receive the message
source.addEventListener('message'.function (evt) {
console.info(evt.data);
});
// Error message, and close notification
source.addEventListener('error'.function (evt) {
// console.info(evt);
}, false);
} else {
alert("Browsers do not support SSE")
}
</script>
Copy the code
The service side DEMO
First declare to the client that the event stream is followed by data of type TEXT /event-stream, and then you can send messages to the client multiple times. The event stream is a simple text stream that supports only utF-8 encoding. Each message is delimited by an empty line.
@RestController
public class SSEsController {
// Send data to the browser
@RequestMapping(value = "/push", produces = "text/event-stream")
public String push(a) throws InterruptedException { String msg = ... ;// Fixed format
return "data:" + msg + "\n\n"; }}Copy the code
SpringBoot uses SseEmitter to support SSE, without the cumbersome code above, interested in baidu
Most of this article is a translation of foreign articles:
- Grokking the System Design Interview by Design Gurus
- www.html5rocks.com/en/tutorial…
- Blog.csdn.net/beng_shakal…
🍎QQ group [837324215] 🍎 pay attention to my public number [Java Factory interview officer], learn together 🍎🍎🍎