Save server resources and achieve two-way data transmission – in-depth analysis of the WebSocket protocol

Jiangcheng Cheerful Pea: Personal homepage

Personal column :《VUE》《javaScript》

Personal website : “Jiangcheng Cheerful Pea”

The ideal of life is for an ideal life!

Table of Contents

? Column introduction

Article introduction

1. What is WebSocket?

2. Characteristics

full duplex

binary frame

Protocol name

shake hands

advantage

2. Application scenarios

?Write at the end


? Column Introduction

Welcome to the front-end entry journey! This column is created for readers who are interested in web development and have just started learning front-end. Whether you are a beginner or a developer with some basic knowledge, we will provide you with a systematic and friendly learning platform here. We update it in the form of questions and answers to present you with selected front-end knowledge points and best practices. By explaining concepts in simple and easy-to-understand terms and providing practical examples and exercises, you can gradually build a solid foundation. Whether it is HTML, CSS, JavaScript or the latest front-end frameworks and tools, we will provide you with rich content and practical skills to help you better understand and apply various technologies in front-end development.

At the same time, we will also pay attention to the latest front-end trends and developments. As Web technology continues to evolve, front-end development is also constantly innovating. We will introduce the latest front-end frameworks, tools and technologies in a timely manner so that you can stay at the forefront and keep pace with the times. By mastering the latest front-end technologies, you will be able to become more competitive in the highly competitive field of web development.

Article introduction

1. What is WebSocket

WebSocket is a network transmission protocol located at the application layer of the OSI model. Full-duplex communication can be performed on a single TCP connection, which can better save server resources and bandwidth and achieve real-time communication.

The client and server only need to complete a handshake, and a persistent connection can be established between the two for bidirectional data transmission.

As can be seen from the picture above, the websocket server and client are connected through a handshake. After the connection is successful, both can actively send or receive data to each other.

Before the emergence of websocket, the way to develop real-time web applications was polling

Keep sending HTTP requests to the server to ask if there is data. If there is data, the server will respond with a response message. If the polling frequency is relatively high, then the effect of “real-time communication” can be achieved approximately

The disadvantages of polling are also obvious. Repeatedly sending invalid query requests consumes a lot of bandwidth and CPU resources.

2. Features

full duplex

Communication allows data to be transmitted in both directions simultaneously. It is equivalent in capability to the combination of two simplex communication methods.

For example, A→B means B→A at the same time, which is instantaneous synchronization.

binary frame

It adopts a binary frame structure, and its syntax and semantics are completely incompatible with HTTP. Compared with http/2, WebSocket focuses more on “real-time communication”, while HTTP/ 2 focuses more on improving transmission efficiency, so the frame structure of the two is also very different.

Unlike HTTP/2, which defines streams, there are no features such as multiplexing and priority.

It is full-duplex by itself and does not require server push.

Protocol name

The ws and wss are introduced to represent the websocket protocols of plaintext and ciphertext respectively, and the default port is 80 or 443, which is almost the same as httpConsistent

ws://www.chrono.com
ws://www.chrono.com:8080/srv
wss://www.chrono.com:445/im?user_id=xxx

handshake

WebSocket also needs a handshake process before it can officially send and receive data.

The format of data sent by the client is as follows:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
  • Connection: Upgrade must be set, indicating that the client wants the connection to be upgraded.
  • Upgrade: Websocket must be set, indicating that you want to upgrade to the Websocket protocol
  • Sec-WebSocket-Key: A base64-encoded ciphertext sent by the client for a simple authentication key. The server is required to return a corresponding encrypted “Sec-WebSocket-Accept response, otherwise the client will throw an error and close the connection.
  • Sec-WebSocket-Version: Indicates the supported Websocket version

Data format returned by the server:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK + xOo=Sec-WebSocket-Protocol: chat
  • HTTP/1.1 101 Switching Protocols: Indicates that the server accepts client connections using the WebSocket protocol
  • Sec-WebSocket-Accep: Verify the client request message, also to prevent incorrect connections. The specific method is to add a dedicated UUID to the value of “Sec-WebSocket-Key” in the request header, and then calculate the digest.

Advantages

  • Less control overhead: The data packet header protocol is smaller, unlike http, which requires a complete header for each request
  • Stronger real-time performance: Compared with HTTP requests, which need to wait for the client to initiate a request before the server can respond, the delay is significantly less.
  • Maintain the created connection state: After establishing communication, the state information can be omitted, unlike HTTP, which requires authentication for each request.
  • Better binary support: Binary frames are defined for better handling of binary content
  • Support extension: users can extend the websocket protocol and implement some customized sub-protocols
  • Better compression effect: With appropriate extension support, Websocket can inherit the context of previous content and significantly improve the compression rate when transmitting similar data.

2. Application scenarios

Based on the characteristics of de facto communication of websocket, its application scenarios include:

  • Barrage
  • media chat
  • Collaborative editing
  • Location-based apps
  • Live sports updates
  • Real-time updates of stock fund quotations

? Write at the end

Please feel free to give me some advice, comment below or send me a private message. Thank you very much.

? I think a certain part of my design is too cumbersome. Is there a simpler or higher-quality packaging method?

? Think some of my code is too old and can provide new API or the latest syntax?

? Don’t understand some of the content in the article

?Answer some questions in my article

? Think that some interactions and functions need to be optimized, and find bugs

? Want to add new features and have better suggestions for the overall design and appearance?

Finally, thank you for your patience in watching. Now that we are here, click Like and go!

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Network Skill TreeHomepageOverview 42,295 people are learning the system