What is the WebSocket

define

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

Relevance and distinction

  • HTTP
  1. HTTP is a non-persistent protocol, and the client can only know the progress of the server through continuous useAjaxPoll or adoptlong pollBut the former puts great pressure on the server, while the latter will block due to waiting for a Response

  2. The keep-alive connection is enabled by default in HTTP1.1, which maintains the TCP channel so that multiple requests can be sent and multiple responses can be received in an HTTP connection, but only one Response can be received in a Request. Moreover, this response is also passive and cannot be initiated actively.

  3. Websocket is a protocol independent of HTTP, but websocket must rely on HTTP to perform operations onceShake handsAfter the handshake is successful, the data is transferred directly through the TCP channel, regardless of HTTP. You can use a graph to understand the intersection of the two, but not all of them.

  • socket
  1. Sockets are also known as socketsThe socketUnlike HTTP and WebSocket, socket is not a protocol. It is an interface encapsulation of the transport-layer protocol (mainly known as TCP/IP) at the program level. Can be thought of as an invocation interface (API) that provides end-to-end communication
  2. For programmers, they need to create A socket instance on the A side, and provide the INSTANCE with the IP address and port number of the B side to connect to, and create another socket instance on the B side, and bind the local port number to listen. After A connection is established between A and B, the two parties establish an end-to-end TCP connection for bidirectional communication. WebSocekt borrows the idea of socket to provide a similar two-way communication mechanism between client and server

Application scenarios

WebSocket can do bullet screen, message subscription, multi-player games, collaborative editing, real-time stock fund quotation, video conference, online education, chat room and other applications real-time monitoring server changes

The Websocket handshake

  • Websocket handshake request packet:
GET/chat HTTP / 1.1

Host: server.example.com

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==

Sec-WebSocket-Protocol: chat, superchat

Sec-WebSocket-Version: 13

Origin: http://example.com

Copy the code

The following are the differences with traditional HTTP packets:

Upgrade: websocket

Connection: Upgrade

Copy the code

Indicates that the WebSocket protocol is initiated

Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==

Sec-WebSocket-Protocol: chat, superchat

Sec-WebSocket-Version: 13

Copy the code

Sec-websocket-key is randomly generated by the browser to verify whether WebSocket communication can take place and prevent malicious or unintentional connections.

Sec_websocket-protocol is a user-defined string used to identify the Protocol required by the service

Sec-websocket-version Indicates the supported WebSocket Version.

  • Server response:
HTTP / 1.1 101 Switching separate Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=

Sec-WebSocket-Protocol: chat

Copy the code

101 Response code Indicates the protocol to be converted.

Connection: Upgrade Indicates a request to Upgrade a new protocol.

Upgrade: websocket indicates that the websocket protocol is upgraded.

Sec-websocket-accept is an sec-websocket-accept Key that is authenticated by the server and encrypted. To prove that the client and server can communicate.

Sec-websocket-protocol Indicates the final Protocol.

At this point, the client and the server have successfully established a Websocket connection, HTTP has done all its work, and it is now time to communicate in full accordance with the Websocket protocol.

About the Websocket

WebSocket heartbeat

Some unknown circumstances may cause the SOCKET to disconnect, but the client and server do not know. The client needs to send a heartbeat Ping periodically to let the server know that it is online, and the server also needs to reply a heartbeat Pong to tell the client that it is available, otherwise it is regarded as disconnected

WebSocket state

The readyState property in a WebSocket object has four states:

  • 0: the connection is ongoing
  • 1: indicates that the connection is successful and the communication is normal
  • 2: the connection is being closed
  • 3: indicates that the connection is closed or fails to be opened

WebSocket practice

The server receives and sends messages

WebSocket server part, this article will be built with Node.js

Install Express and WS which handles the WebSocket protocol:

npm install express ws

Copy the code

Package. json after successful installation:


Then create the server.js file in the root directory:

// Introduce Express and WS

const express = require('express');

const SocketServer = require('ws').Server;



// Specify the port number to enable

const PORT = 3000;



// Create express, bind to listen on port 3000, and enable consol prompt

const server = express().listen(PORT, () => console.log(`Listening on ${PORT}`));



// Deliver express to SocketServer to enable WebSocket services

const wss = new SocketServer({ server });



// Execute when WebSocket is connected from outside

wss.on('connection', (ws) => {

  // Execute this console prompt when connecting

  console.log('Client connected');



  // Set the listener on message to receive messages sent from the client

  ws.on('message', (data) => {

    //data is the message sent by the client, which is returned intact

    ws.send(data);

  });



  // Execute when the WebSocket connection is closed

  ws.on('close', () = > {

    console.log('Close connected');

  });

});

Copy the code

Run the Node server.js command to start the service. After the port is opened, a message is displayed indicating that the service is successfully started


After WebSocket is enabled, the server listens in message, receives data to capture messages sent by the client, and sends messages using SEND

The client receives and sends messages

Create index.html and index.js files in the root directory, respectively

  • index.html
<html>

  <body>

    <script src="./index.js"></script>

  </body>


</html>

Copy the code
  • index.js
// Open the connection to the server using the WebSocket address

let ws = new WebSocket('ws://localhost:3000');



// The enabled action specifies the event to be executed after the connection

ws.onopen = (a)= > {

  console.log('open connection');

};



// Receives the message sent by the server

ws.onmessage = (event) = > {

  console.log(event);

};



// Specifies the event to execute after shutdown

ws.onclose = (a)= > {

  console.log('close connection');

};

Copy the code

The url above is the address of the local node to enable the service, specify connection (onopen), close (onClose), and receive (onMessage) execution events, access HTML, and print WS information


If an Open Connection is displayed, the connection is successful and the client uses onMessage to receive the message

The event parameter contains the detailed information about the communication, and the message returned from the server will be in the data attribute of the event.

Manually call SEND on the console to send messages and print event messages:


The server sends the data periodically

The message is sent from the client and sent back from the server. We can also use setInterval to have the server send messages to the client at a fixed time:

Server.js is modified as follows:

// Execute when WebSocket is connected from outside

wss.on('connection', (ws) => {

// Execute this console prompt when connecting

  console.log('Client connected');



+ // Constantly sends the latest messages to the client

+ const sendNowTime = setInterval(() => {

+ ws.send(String(new Date()));

+}, 1000);



- // Set the listener on message to receive messages sent from the client

- ws.on('message', (data) => {

- //data indicates the message sent by the client, and returns the message intact

- ws.send(data);

-});



// Execute when the WebSocket connection is closed

  ws.on('close', () => {

    console.log('Close connected');

  });

});

Copy the code

The client will receive the connection periodically until we shut down the WebSocket service


Many people chat

If multiple client connections return only the messages sent by each client in the same way as above, first comment the server to send the message periodically, and enable two window emulation:


What if we wanted to share messages between clients and also receive messages back from the server?

We can use clients to find all currently connected clients and send a postback message to each client:

Modify server.js as follows:

.



// Execute when WebSocket is connected from outside

wss.on('connection', (ws) => {

// Execute this console prompt when connecting

  console.log('Client connected');



- // Periodically sends the latest messages to the client

- const sendNowTime = setInterval(() => {

- ws.send(String(new Date()));

-}, 1000);



+ // Set the listener on message to receive messages sent from the client

+ ws.on('message', (data) => {

+ // Get all connected clients

+ let clients = wss.clients;

+ // loop to send messages to each client

+ clients.forEach((client) => {

+ client.send(data);

+});

+});



// Execute when the WebSocket connection is closed

  ws.on('close', () => {

    console.log('Close connected');

  });

});

Copy the code

This way, no matter which client sent the message, the server can send the message back to each client:You can observe the connection information:


Conclusion 🥇

On paper come zhongjue shallow, must know this to practice, I hope you can put the theory with the above example for digestion, build a good server can also directly use test tools to play a wave


Refer to the article 📜

❤️ Ruan Yifeng -WebSocket tutorial

❤️ Using WebSockets on Heroku with Node.js

What is the principle of ❤️ WebSocket? Why can persistent connection be implemented?

Extension 🏆

If you find this article helpful, check out my other articles at ❤️ :

👍 5 Design patterns to know for Web development 🍊

👍 10 simple tips to make your vue.js code more elegant 🍊

👍 Data structures Web developers should know about 🍊

👍 classic interview questions! From entering urls to displaying pages, why don’t you start learning? 🍊

👍 The handshake process of the SSL protocol 🍊