search
HomeWeb Front-endH5 TutorialIn-depth understanding of Websocket principles

This article introduces to you an in-depth understanding of the principles of Websocket. It has good reference value. I hope it can help friends in need. 

1. websocket and http

WebSocket is a thing (protocol) created by HTML5, which means that the HTTP protocol has not changed, or it doesn’t matter, but HTTP does not support persistent connections (long-term connections). Connections, circular connections are not counted)

First of all, HTTP has 1.1 and 1.0, which is the so-called keep-alive. Multiple HTTP requests are merged into one, but Websocket is actually a new protocol, which has basically nothing to do with the HTTP protocol. It is just for compatibility with the handshake specifications of existing browsers, which means that it is based on the HTTP protocol. A supplement can be understood through such a picture

There are intersections, but not all.

In addition, Html5 refers to a series of new APIs, or new specifications and new technologies. The Http protocol itself only has 1.0 and 1.1, and has no direct relationship with Html itself. . In layman's terms, you can use the HTTP protocol to transmit non-HTML data, that's it =. =

To put it simply, the levels are different.

2. What kind of protocol is Websocket and what are its specific advantages

First of all, Websocket is a persistent protocol, compared to a non-persistent protocol like HTTP. Let’s give a simple example and use the PHP life cycle that is currently widely used to explain.

The life cycle of HTTP is defined by Request, that is, one Request and one Response, then in HTTP1.0 , this HTTP request ends.

Improvements were made in HTTP 1.1 so that there is a keep-alive, that is, in one HTTP connection, multiple Requests can be sent and multiple Responses can be received. But please remember Request = Response, this is always the case in HTTP, which means that a request can only have one response. Moreover, this response is also passive and cannot be initiated actively.

Coach, you have done so much, what does it have to do with Websocket? _(:з ∠)_Okay, I was about to talk about Websocket. .

First of all, Websocket is based on the HTTP protocol, or it borrows the HTTP protocol to complete part of the handshake.

First let’s look at a typical Websocket handshake (borrowed from Wikipedia...)

GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13Origin: http://example.com

Children’s shoes who are familiar with HTTP may have discovered that this handshake is similar to the HTTP protocol There are a few more things in the request. I will explain the function by the way.

Upgrade: websocketConnection: Upgrade

This is the core of Websocket. Tell Apache, Nginx and other servers: Pay attention, I initiated the Websocket protocol, help me find the corresponding one quickly. Assistant processing ~ not that old-fashioned HTTP.

Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13

First of all, Sec-WebSocket-Key is a Base64 encode value, which is randomly generated by the browser and tells the server: peat, don’t fool me. , I want to verify whether Ni is really the Websocket Assistant.

Then, Sec_WebSocket-Protocol is a user-defined string used to distinguish the protocols required by different services under the same URL. Simple understanding: I want to serve A tonight, make no mistake~

Finally, Sec-WebSocket-Version tells the server the Websocket Draft (protocol version), at the beginning, the Websocket protocol was still in the Draft stage. There were all kinds of weird protocols, and there were also many weird and different things. What Firefox and Chrome didn’t use? A version and the like, there were too many Websocket protocols, which was a big problem. . But it’s okay now, it’s been settled ~ Something everyone uses ~ Dehydration: Waiter, I want a 13-year-old →_→

Then the server will return the following things , indicating that the request has been accepted and the Websocket has been successfully established!

HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat

This is the last area responsible for HTTP. Tell the client that I have successfully switched the protocol~

Upgrade: websocketConnection: Upgrade

It is still fixed and tells the client that the upcoming upgrade is Websocket protocol, not mozillasocket, lurnarsocket or shitsocket.

Then, Sec-WebSocket-Accept is the Sec-WebSocket-Key that has been confirmed by the server and encrypted. Server: Okay, okay, I understand. Let me show you my ID CARD to prove it. . After

, Sec-WebSocket-Protocol represents the final protocol used.

At this point, HTTP has completed all its work, and the next step is to proceed completely in accordance with the Websocket protocol. The specific agreement is not explained here.

——————Technical analysis part completed——————

You have been BBBing for so long, so what is the use of Websocket? http long poll, or ajax polling can realize real-time information transmission.

Okay, young people, let’s talk about the use of Websocket. Let me give you some carrot (su) radish (dan) radish (red)

3. The role of Websocket

Before talking about Websocket, I will By the way, let’s talk about the principles of long poll and ajax polling.

ajax polling

The principle of ajax polling is very simple. Let the browser send a request every few seconds to ask the server if there is new information.

Scene reproduction:

Client: La la la, is there any new information (Request)

Server: No (Response)

Client : La la la, is there any new information (Request)

Server: No. . (Response)

Client: La la la, is there any new information (Request)

Server: You are so annoyed, there is no. . (Response)

Client: La la la, is there any new message (Request)

Server: Okay, okay, I have it for you. (Response)

Client: La la la, is there any new message (Request)

Server:. . . . . without. . . . without. . . No (Response) —- loop

long poll

long poll In fact, the principle is similar to ajax polling, both use polling. , but it adopts a blocking model (keep calling and don't hang up if you don't receive the call). That is to say, after the client initiates the connection, if there is no message, the Response will not be returned to the client. It does not return until there is a message. After returning, the client establishes the connection again, and the cycle starts again.

Scene reproduction:

Client: La la la, is there any new information? If not, just wait until it is available before returning it to me (Request)

Server: Forehead. . Wait until there is news. . Come to you (Response)

Client: La la la, is there any new information? If not, just wait until it is available before returning it to me (Request) -loop

You can see it from above In fact, these two methods are constantly establishing HTTP connections and then waiting for the server to process them, which can reflect another characteristic of the HTTP protocol, passivity.

What is passivity? In fact, the server cannot actively contact the client, it can only be initiated by the client.

To put it simply, the server is a very lazy refrigerator (this is a joke) (it cannot, cannot actively initiate a connection), but the boss has an order. If a customer comes, he must receive it well no matter how tired he is. .

After talking about this, let’s talk about the above flaws (forgive me for talking so much nonsense, OAQ)

It’s easy to see from the above, no matter what, the above two are Very resource consuming.

ajax polling requires the server to have fast processing speed and resources. (Speed) Long poll requires high concurrency, which means the ability to receive customers at the same time. (Site size)

So ajax polling and long poll may happen.

Client: La la la la, is there any new information?

Server: The monthly line is busy, please try again later (503 Server Unavailable)

Client:. . . . Okay, la la la, any new information?

Server: The monthly line is busy, please try again later (503 Server Unavailable)

Client: Then the server is very busy on the side: refrigerator, I want more refrigerators ! More. . More. . (I was wrong... This is another joke...)

Let's get back to the point, let's talk about Websocket

Through the above example, we can see that neither of these two methods is the best. method requires a lot of resources.

One needs faster speeds, one needs more 'phones'. Both of these will lead to an increasing demand for 'phones'.

Oh, by the way, I forgot to mention that HTTP is still a stateful protocol.

To put it simply, the server has to deal with too many customers every day, so he is a forgetful ghost. As soon as you hang up the phone, he will forget all your things and throw away all your things. You have to tell the server again the second time.

So in this case, Websocket appeared. He solved these problems of HTTP. First, passivity. After the server completes the protocol upgrade (HTTP->Websocket), the server can actively push information to the client. So the above scenario can be modified as follows.

Client: La la la, I want to establish the Websocket protocol, required services: chat, Websocket protocol version: 17 (HTTP Request)

Server: ok, confirmed, upgraded to Websocket Protocol (HTTP Protocols Switched)

Client: Please push it to me when you have information. .

Server: ok, I will tell you sometimes.

Server: balabalabalabala

Server: balabalabalabala

Server side: Hahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahaha. A steady stream of information is transmitted. (In programming, this design is called a callback, that is: notify me when you have information, instead of me stupidly running to ask you every time)

Such a protocol solves the delay in the above synchronization. It is also very resource consuming. So why does he solve the problem of consuming resources on the server?

In fact, the program we use has to go through two layers of proxies, that is, the HTTP protocol is parsed by servers such as Nginx, and then transmitted to the corresponding Handler (PHP, etc.) for processing. Simply put, we have a very fast

Operator (Nginx)

who is responsible for transferring the problem to the corresponding

Customer Service (Handler)

. The operator itself is basically fast enough, but every time I get stuck in the customer service (Handler), the customer service processing speed is always too slow. , resulting in insufficient customer service. Websocket solves such a problem. After it is established, you can directly establish a persistent connection with the operator. When there is information, the customer service will find a way to notify the operator, and then the operator will transfer it to the customer. This can solve the problem of slow customer service processing speed.

At the same time, in the traditional way, the HTTP protocol must be continuously established and closed. Since HTTP is non-stateful,

identity info

(identification information) must be retransmitted every time. Tell the server who you are.

Although the operator is very fast, the efficiency will be reduced if he has to listen to so much every time. At the same time, he has to constantly transfer this information to customer service, which not only wastes the customer service's processing time, but also causes Consumes excessive traffic/time in network transmission. But Websocket only requires one HTTP handshake, so the entire communication process is established in one connection/state, which avoids the non-statefulness of HTTP. The server will always know your information until you close it. request, this solves the problem that the operator has to repeatedly parse the HTTP protocol and check the identity info information.

At the same time, the client takes the initiative to ask, and the server (push) sends it when there is information (of course, the client still waits for the initiative to send information...), and when there is no information, it is handed over to the operator (Nginx) , there is no need to occupy the customer service (Handler) which is inherently slow.

As for how to use Websocket on a client that does not support Websocket. . The answer is:

Can't

But you can simulate a similar effect by using the long poll and

ajax polling

mentioned aboveRelated recommendations:

HTML imitation of Baidu homepage

The role of meta in the html page and the analysis of the cache and non-caching settings of the page

The above is the detailed content of In-depth understanding of Websocket principles. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)