This article was originally posted on my personal website: www.jianfengke.com/
What’s the WebSocket
Websocket is a persistent network communication protocol that can carry out full-duplex communication on a single TCP connection. Without the concepts of Request and Response, the two are completely equal. Once the connection is established, two-way data transmission can be carried out between the client and the server in real time.
WebSocket is different from Http
- HTTP is a non-persistent protocol, and the client can only know the processing progress of the server by using Ajax polling or using long poll. However, the former puts great pressure on the server, while the latter will block due to waiting for Response all the time
- Websocket is a protocol independent of HTTP. However, websocket must use HTTP to carry out a handshake (the handshake is the same). After the handshake is successful, data is directly transmitted through the TCP channel, regardless of HTTP
WebSocket application
Thanks to the full-duplex communication mechanism of Websocket, Websocket can monitor server changes in real-time for applications such as bullet screen, message subscription, multi-player game, collaborative editing, real-time stock fund quotation, video conference, online education, chat room and so on.
Quick access to WebSocket usage, both client and server
First, we wanted to build something like this:
- The client (front-end page, can be multiple, on behalf of different users) establishes socket connection with the server. When establishing the connection, both the client and the server respond (such as output: join webSocket connection).
- The client sends a message. After receiving the message, the server sends a specific message back to the client
- Any client sends a message, and the server receives the message and broadcasts it to all clients
The tool we use is very simple, a socket package: WS we install from scratch should look like this:
Create a folder, for example, socket-test, to access the directory
mkdir socket-test
cd socket-test
Copy the code
Create an index.js file to start the server socket service
touch index.js
Copy the code
Initialize NPM and install WS
npm init -y
npm i ws
Copy the code
According to the WS documentation, quickly start a Websocket service, as specified on port 9003
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 9003
})
wss.on("connection", ws => {// Listen for a callback when a client is connected to the socket service. The related interface operation of WS is for the current sending client console.log('Join webSocket connection') ws.on('open', () => {// When the listener detects that the connection is started, a message indicating that the connection is successful will be returned to the corresponding client ws.send('Connection open'); }); ws.on('message', (data) => {// The connection starts to listen on the client, and triggers a callback as soon as a message is sentWs. Send (' You sent the following message:${data}`) }); }) Copy the code
That’s it, a simple WebSocket server, you read that right, just a few lines of code.
Initialize a client page:
Ok now to initialize a client page: client1.html created in the same directory:
<! DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title> Client 1</title></head> <body> </body> <script> let ws = new WebSocket("ws://localhost:9003") ws.onopen = () => { console.log('Enabled') } ws.onmessage = event => { console.log('Client 1 receives a server message :', event.data) } ws.onclose = () => { console.log('Closed'); } </script> </html> Copy the code
Start the service
Ok, so far the client and server are ready, start them separately. Start the server:
node index.js
Or nodemon index.js(recommended)Copy the code
Start the client: This page can be started directly by using the liveServer plugin.
Now it’s all up:
The server output a messageClient tip:
WebSocket instance
Let’s take a look at what the client websocket instance contains:
WebSocket constructor is a browser native interface, dedicated to WebSocket communication, the connection mode is also very simple, the server address as a construction parameter passed in, and then instantiated to complete the Websoket connection. If you are not familiar with WebSocket, you can click here to see the documentation and usage: WebSocket Doc We can see some properties and methods in the example above. We can see that onclose and onMessage have defined callback methods. The URL property represents the address of the current WebSocket connection. The focus is on how the client sends messages to the server. As simple as this, the instance has a send method, which is executed as an argument to send a message.
The client sends the message
Now send a message to the server:
ws.send('Hello duck')
Copy the code
After sending, the server returns the message immediately after receiving it:
Yes, this is the basic flow of socket communication, chat room principle with this is almost the same
Implement broadcast function
If there are multiple clients, and any client sends a message, the server broadcasts the message to all of them, how does this work?
First add a client page, client2.html
<! DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title> Client 2</title></head> <body> </body> <script> let ws = new WebSocket("ws://localhost:9003") ws.onopen = () => { console.log('Enabled') } ws.onmessage = event => { console.log('Client 2 receives a server message :', event.data) } ws.onclose = () => { console.log('Closed'); } </script> </html> Copy the code
To be clear, by default, the server is aware of which client instance is sending a message to the server. Ws-send is only sent to the corresponding client and does not affect other clients.
To implement the broadcast function, we need to make a small change to the server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 9003
})
wss.on("connection", ws => {// Listen for a callback when a client is connected to the socket service. The related interface operation of WS is for the current sending client console.log('Join webSocket connection') ws.on('open', () => {// When the listener detects that the connection is started, a message indicating that the connection is successful will be returned to the corresponding client ws.send('Connection open'); }); ws.on('message', (data) => {// The connection starts to listen on the client, and triggers a callback as soon as a message is sent// Get all connected clients let clients = wss.clients; // loop to send messages to each client clients.forEach((client) => { Client. Send (' You send the following message:${data}`); }); }); }) Copy the code
The core is to go back to the currently connected client instance via wsS. clients, iterate over the send message and now send the message from client 1 to see if client 2 can receive it.
Client 1:Client 2:
Both receive the broadcast message from the server and the message is broadcast
At the end
After such a small chestnut tamper, is it to WebSocket understand a lot? In fact, its function is far more than this, we go to explore, remember what good practice remember to recommend to me ah, refueling refueling…
This article is formatted using MDNICE