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.
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.
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)
Before talking about Websocket, I will By the way, let’s talk about the principles of long poll
and 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
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...)
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'tBut you can simulate a similar effect by using the long poll and
ajax polling mentioned aboveRelated recommendations:
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!