Table of Contents
1. websocket and http
2. What kind of protocol is Websocket and what are its specific advantages
3. The role of Websocket
ajax polling
long poll
Let's get back to the point, let's talk about Websocket
Home Web Front-end H5 Tutorial In-depth understanding of Websocket principles

In-depth understanding of Websocket principles

Jul 28, 2018 am 10:52 AM
websocket

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
Copy after login

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
Copy after login
Copy after login

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
Copy after login

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
Copy after login

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

Upgrade: websocketConnection: Upgrade
Copy after login
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

See all articles