Read more articles in the series at myMaking a blog, please visit the sample codeHere,.
The advantage of WebSocket
-
High performance.
Depending on the test environment data, this is about 2-10 times higher than a normal Ajax request. HTTP is a text protocol with a large amount of data.
WebSocket is a binary-based protocol that uses text data to set up a connection, but transmits binary data later, thus providing better performance than Ajax requests.
-
Two-way communication.
If it’s a normal Ajax request that needs to get the data in real time, you can only send the request with a timer, which wastes server resources and traffic.
With WebSocket, the server can proactively send information to the forward end.
-
High safety
Since WebSocket is relatively new, it is more secure than HTTP.
Next, try to set up a webSocket-based two-way communication with socket. IO.
Socket.io
Socket. IO is a common library used when using WebSocket. It automatically determines that WebSocket is used in browsers that support WebSocket, and other browsers use Flash for communication.
- The operation is simple
- Compatible with low-end browsers such as IE6
- Automatic data parsing
- Automatic reconnection If a connection is disconnected, the WebSocket automatically reconnects.
Set up a WebSocket application using socket. IO
Server example code: /lesson19/server.js
const http = require('http')
const io = require('socket.io') // 1. Set up the HTTP server. const server = http.createServer((req, res) => { }) server.listen(8080) // 2. Set up a WebSocket and have Socket. IO listen to the HTTP server. If it finds a WebSocket request, it will automatically process it. Const ws = io.listen(server) // After the connection is established, the connection event is triggered. / / this event will return a socket object (https://socket.io/docs/server-api/#Socket), can use the Socket object to send and receive data operation.
ws.on('connection', (socket) => {// According to the event name, send data to the client, the amount of data is unlimited. socket.emit('msg'.'Server sends first data to client'.'Server sends data to client # 2') // Receive data from the client based on the event name socket.on('msg', (... MSGS) => {console.log(MSGS)}) // Use a timer to send data to the clientsetInterval(() => {
socket.emit('timer', new Date().getTime())
}, 500);
})
Copy the code
Client example code: /lesson19/index.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <! IO is already listening for requests from the HTTP server. Once a request is received for this file, it will automatically return this file. No developer configuration is required. -- > <! /node_modules/socket. IO /node_modules/socket.io-client/dist/socket.io.js --> <script SRC ="http://localhost:8080/socket.io/socket.io.js">< span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; word-break: inherit! Important;" const socket = io.connect('ws://localhost:8080/') // According to the event name, send data to the server, the amount of data is unlimited. socket.emit('msg'.'Client sends first data to server'.'Client sends data to server # 2') // Receive the data returned by the server based on the event name'msg', (... MSGS) => {console.log(MSGS)})'timer', (time) => {
console.log(time)
})
</script>
</body>
</html>
Copy the code
Open index. HTML in a browser and see the printed message in the console.