The following is a summary of reference learning
Traditional Polling
In current Web applications, it is a common continuous communication mode, which is usually implemented by setInterval or setTimeout. For example, if we wanted to periodically fetch and refresh data on a page, we could write the following implementation in combination with Ajax:
setInterval(function() {
$.get("/path/to/server".function(data, status) {
console.log(data);
});
}, 10000);Copy the code
The program requests data from the server every 10 seconds and stores it when it arrives. This method usually can meet the requirements of simple, yet at the same time there are a lot of defects: under the condition of the network is not stable, the server receives the request, sends a request to the client receives the request total time could be more than 10 seconds, and the request is sent 10 seconds interval, this will lead to the received data to arrive at the order in which they do not agree with the order. So there is polling using setTimeout:
function poll() {
setTimeout(function() {
$.get("/path/to/server".function(data, status) { console.log(data); Poll (); }); }, 10000); }Copy the code
The program is set to initiate a request 10 seconds after the data is returned, then initiate a second request 10 seconds after the data is returned, and so on. This does not guarantee a fixed time interval between requests, but it does guarantee the order in which the data arrives.
defects
The program creates a new HTTP request for each request, but does not always return the required new data. When the number of simultaneous requests reaches a certain level, the load on the server becomes heavy.
Long Poll
After the client sends a request, the server takes the connection and returns a response to the client if there is a message. No message, no response is returned. The client then sends the request again, repeating the previous action.
conclusion
The HTTP protocol is characterized by the fact that the server cannot initiate contact with the client. Its passivity indicates that the two-way communication needs to be continuously connected or always open, which requires fast processing speed or high concurrency capacity of the server and is very resource-consuming.
What is the websocket?
Websocket is a new protocol of HTML5, it allows the server to pass information to the client, browser and client duplex communication
The story
Because 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. We can only use “polling” : every once in a while a query is issued, which is inefficient and wasteful (because you have to keep connecting, or HTTP connections are always open). So engineers have been wondering if there is a better way. That’s how WebSocket was invented.
The characteristics of the websocket
The server can take the initiative to push information to the client, and the client can also take the initiative to send information to the server, which is a real two-way equal dialogue and belongs to a server push technology.
- It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers.
- It is based on TCP and belongs to the application layer with HTTP
- The data format is relatively light, with low performance overhead and high communication efficiency.
- You can send text or binary data.
- There are no same-origin restrictions, and clients can communicate with any server
- The protocol identifier is WS (or WSS if encrypted) and the server URL is the URL, such as WS ://localhost:8023
Socket. IO, a cross-platform WebSocket communication library
Cross-platform WebSocket communication library, with front and back end consistent API, can trigger and respond to custom events. The two core APIS of socket. IO are emit and ON, which are available on both the server and the client. Two-way communication between the server and client can be realized through EMIT and ON.
- Emit: Emits an event. The first parameter is the event name, the second parameter is the data to be sent, and the third parameter is the callback function.
- On: listens for an event emitted from the emit emit. The first argument is the name of the event to listen for. The second argument is the callback function used to receive the received data.
The service side
var app = require('express') ();var http = require('http');
var socketio = require("socket.io");
const server = http.createServer(app)
const io = socketio(server)
var count = 0;
// WebSocket connects to the server
io.on('connection', (socket)=> {
//// All event-triggered responses are written here
setInterval((a)= >{
count++
// Send a message to the client establishing the connection
socket.emit('mynameEv', { name:"You and I."+count})
},1000)
// Listen for the client to send messages
socket.on('yournameEv'.function (data) {
console.log(data)
})
})
app.get('/'.function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// Enable port 3000
server.listen(3000)Copy the code
The client
<body>
<div id="myname"></div>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var count = 0;
const socket = io.connect('http://localhost:3000')
socket.on('mynameEv', (data)=>{
document.getElementById("myname").innerHTML = data.name;
console.log(data.name)
setInterval(()=>{
count++
socket.emit('yournameEv', { name:"Fly xuan"+count})
},1000)
})
</script>
</body>Copy the code