preface
With the development of The Web, users have higher and higher requirements for real-time push of the Web. For example, industrial operation monitoring, Web online communication, instant quotation system, online games, etc., all need to actively and real-time transfer the changes occurring in the background to the browser, without users manually refreshing the page. This paper compares and summarizes the past and present popular Web real-time push technologies.
This article complete source code please jabberMaking a blog, the paper comes zhongjue shallow, I suggest you start to knock on the code.
Two-way communication
The HTTP protocol has a flaw: communication can only be initiated by the client. For example, if we want to know today’s weather, the client can only send a request to the server, and the server returns the query result. The HTTP protocol does not allow the server to actively push information to the client. The nature of this one-way request makes it very difficult for the client to know if the server has continuous state changes. Before the WebSocket protocol, there were three ways to achieve two-way communication: polling, long-polling, and iframe streaming.
1. Polling
Http headers are sent each time a request is sent, which can be a drain on traffic and CPU utilization
- Advantages: Simple implementation without too many changes
- Disadvantages: The polling interval is too long, so users cannot receive the updated data in time. If the polling interval is too short, too many query requests will be made, which will increase the burden on the server
// 1.html
<div id="clock"></div>
<script>
let clockDiv = document.getElementById('clock');
setInterval(function() {let xhr = new XMLHttpRequest;
xhr.open('GET'.'/clock'.true);
xhr.onreadystatechange = function() {if(xhr.readyState == 4 && xhr.status == 200){ console.log(xhr.responseText); clockDiv.innerHTML = xhr.responseText; } } xhr.send(); }, 1000); </script>Copy the code
// Polls the serverlet express = require('express');
let app = express();
app.use(express.static(__dirname));
app.get('/clock'.function(req,res){
res.end(new Date().toLocaleString());
});
app.listen(8080);
Copy the code
Start a local service, open http://localhost:8080/1.html, get the following results:
2. Long polling (long-polling)
It is a waste of network bandwidth
- Advantages: Polling has been optimized, with better timeliness
- Disadvantages: Maintaining connections consumes resources; Server did not return valid data, program timed out.
<div id="clock"></div>
<script>
let clockDiv = document.getElementById('clock')
function send() {
let xhr = new XMLHttpRequest()
xhr.open('GET'.'/clock'.true) xhr.timeout = 2000 // Timeout duration in milliseconds xhr. onreadyStatechange =function() {
if (xhr.readyState == 4) {
if(xhr.status == 200) {// If the return is successful, Clockdiv.innerhtml = xhr.responseText} send() // The next request will be sent with or without success}} xhr.onTimeout =function() {
send()
}
xhr.send()
}
send()
</script>
Copy the code
3. Iframe streaming
- Advantages: Messages can arrive in real time; Browser compatibility
- Disadvantages: Server maintenance of a long connection will increase overhead; Internet Explorer, Chrome, and Firefox will display the loading is not complete, and the icon will keep rotating.
// 3.html
<body>
<div id="clock"></div>
<iframe src="/clock" style="display:none"></iframe>
</body>
Copy the code
/ / the iframe flowlet express = require('express')
let app = express()
app.use(express.static(__dirname))
app.get('/clock'.function(req, res) {
setInterval(function() {
let date = new Date().toLocaleString()
res.write(`
<script type="text/javascript">
parent.document.getElementById('clock').innerHTML = "${date}"; // Change the parent dom element </script> ')}, 1000)}) app.listen(8080)Copy the code
Start a local service, open http://localhost:8080/3.html, get the following results:
In the above code, the client requests only once, while the server keeps sending data to the client, making it expensive for the server to maintain a long connection.
We have introduced three real-time push technologies above, but their shortcomings are obvious and they are not ideal in use. Next, we will focus on another technology — Websocket, which is an ideal two-way communication technology.
Second, the WebSocket
1. What is websocket
WebSocket is a completely new protocol, and with the improvement of the HTML5 draft, more and more modern browsers begin to fully support WebSocket technology, which attaches the TCP Socket to the webpage, setting up a link with the communicating party that remains active.
Once the WebSocket protocol communication connection is established between the Web server and the client, all subsequent communication depends on this special protocol. Data in any format, such as JSON, XML, HTML or images, can be sent to each other during communication. Because it is a protocol based on HTTP, the initiator of the connection is still the client. Once the WebSocket communication connection is established, either the server or the client can directly send packets to the other party.
People who are new to WebSocket ask the same question: Why do we need another protocol when we already have HTTP?
2. Limitations of HTTP
- HTTP is a half-duplex protocol, that is, data flows in only one direction at a time. The client sends a request to the server (one-way), and the server responds to the request (one-way).
- The server cannot actively push data to the browser. This makes some advanced features difficult to implement, such as chat room scenarios.
3. The characteristics of the WebSocket
- Support two-way communication, more real-time
- You can send text or binary data
- Reduce traffic: As long as a WebSocket connection is established, you want it to stay connected. Not only is the total overhead per connection reduced compared to HTTP, but there is also less traffic due to the small size of the WebSocket header
Compared with the traditional HTTP request-response mode that requires the client to establish a connection with the server, WebSocket is a TCP long-connection communication mode similar to Socket. Once the WebSocket connection is established, subsequent data is transmitted in the form of frame sequence. Before the client disconnects from the WebSocket or the Server, the client and Server do not need to initiate a connection request again. In the case of massive concurrency and heavy load traffic between the client and server, it greatly saves the consumption of network bandwidth resources and has obvious performance advantages. In addition, the client sends and receives messages on the same persistent connection, which has obvious real-time advantages.
Let me take a look at how Websocket implements two-way communication between client and server:
// websocket.html
<div id="clock"></div>
<script>
let clockDiv = document.getElementById('clock')
let socket = new WebSocket('ws://localhost:9999'// The callback function socket.onopen = is executed when the connection is successfulfunction() {
console.log('Client connected successfully'// Send a message to the server socket.send('hello'Socket.onmessage = = = = = = = = = = = = = = = = = = = = = = = = =function(event) {
clockDiv.innerHTML = event.data
console.log('Received a response from the server', event.data)
}
</script>
Copy the code
// websocket.js
let express = require('express')
letApp = express() app.use(express.static(__dirname)) // HTTP server app.listen(3000)let WebSocketServer = require('ws').server // Start a websocket Server with the WS module and listen on port 9999letwsServer = new WebSocketServer({ port: // Socket represents a client, not shared by all clients, but each client has a socket wsServer.on('connection'.function(socket) {// Each socket has a unique ID attribute console.log(socket) console.log(socket)'Client connected successfully'Socket. On (socket.'message'.function(message) {
console.log('Message received from client', message)
socket.send('Server responds :' + message)
})
})
Copy the code
Start a local service, open http://localhost:3000/websocket.html, get the following results:
Third, the comparison of Web real-time push technology
way | type | The technical implementation | advantages | disadvantages | Applicable scenario |
---|---|---|---|---|---|
Polling Polling | The client and server | Client loop requests | 1, simple implementation 2, support cross-domain | 1. Waste of bandwidth and server resources. 2. Most of a request information is useless (complete HTTP header information) | Suitable for small applications |
Long Polling Long Polling | The client and server | The server holds the connection until it has data or times out, reducing the number of repeated requests | 1, simple implementation 2, do not frequently send requests 3, save traffic 4, low latency | (1) The server holds the connection and consumes resources. (2) A request for information is mostly useless | WebQQ, Hi web version, Facebook IM |
Long connection iframe | The client and server | Embed a hidden iframe in the page, set the SRC attribute of the IFrame to a request for a long connection, and the server can stream data to the client. | 1, real-time data delivery 2, do not send useless requests, one link, multiple “push” | 2. The connection status cannot be accurately known. 3 | Gmail chat |
WebSocket | Server ⇌ client | new WebSocket() | 1, support two-way communication, real-time stronger 2, can send binary files 3, reduce traffic | 2. Disconnection and reconnection are not supported | Online games, banking interactions and payments |
To sum up: Websocket protocol not only solves the passivity of the SERVER in HTTP protocol, that is, communication can only be initiated by the client, but also solves the problem of delayed data synchronization and brings obvious performance advantages. Therefore, Websocket is an ideal solution for real-time Web push technology. However, if you want to be compatible with browsers of lower versions, Consider polling.
To recommend a good BUG monitoring toolFundebug, welcome free trial!
Welcome to pay attention to the public number: front-end craftsmen, we will witness your growth together! If you feel rewarded, you are welcome to give me a tip to encourage me to export more quality open source content
Refer to the article
- WebSocket tutorial
- Everest front-end architecture class
- Summary of Web real-time push technology
- WebSocket (1) : Evolution of “real-time push” on the server
- Long connection/Websocket /SSE and other mainstream server push technology comparison