The principle of websocket, and the relationship with HTTP

Source: Internet
Author: User
Tags base64 encode

WebSocket is a protocol in the HTML5 that supports persistent connections, while the HTTP protocol does not support persistent connections.

First of all, HTML5 refers to a series of new APIs, or new specifications, technologies. WebSocket is a new protocol and new API in HTML5.

The HTTP protocol itself is only 1.0 and 1.1, the so-called keep-alive, merging multiple HTTP requests into one.

Second, WebSocket is what kind of agreement, concrete has what merit.

First, WebSocket is a persistent protocol relative to HTTP, a non-durable protocol.

To illustrate:

(1) The HTTP lifecycle is defined by request, which is the request for a response, and in the Http1.0 protocol, the HTTP requests are ended.

Improved in Http1.1, yes there is a keep-alive, that is, in an HTTP connection, you can send multiple request to receive multiple response.

It must be remembered, however, that a request in HTTP can only correspond to a response, and that the response is passive and cannot be actively initiated.

(2) WebSocket is based on the HTTP protocol, or borrowed the HTTP protocol to complete a part of the handshake, in the handshake phase and HTTP is the same.


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
Familiar with the HTTP children's shoes may have found, this is similar to the HTTP protocol handshake request, a few more things.
I'll explain the effect by the way.
Upgrade: websocketConnection: Upgrade
This is the core of WebSocket, tell Apache, Nginx and other servers: Notice, the nest initiates is the WebSocket agreement, quickly help me to find the corresponding assistant processing ~ Not that old-fashioned HTTP.
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13
First, Sec-websocket-key is the value of a Base64 encode, which is randomly generated by the browser, telling the server: Peat, don't confuse the nest, I want to verify that Nikki is not really websocket assistant.
Then, Sec_websocket-protocol is a user-defined string used to distinguish between the protocols required for different services under the same URL. Simple to understand: tonight I'm going to serve a, don't be mistaken.
Finally, Sec-websocket-version is to tell the server to use the WebSocket Draft (protocol version), at the outset, WebSocket protocol is still in the Draft stage, a variety of bizarre protocols have, And there are a lot of weird different things, what Firefox and Chrome is not a version of the same, the original WebSocket protocol too much is a big problem. But now it is OK, has been set up ~ ~ We all use a thing ~ dehydration: Waiter, I want a 13-year-old. Oh, →_→ .

Then the server will return the following things, indicating that the request has been accepted, the successful establishment of WebSocket!
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat
Here at the beginning is the HTTP last responsible area, tell the customer, I have successfully switched the protocol ~
Upgrade: websocketConnection: Upgrade
is still fixed, telling the client that the WebSocket protocol is about to be upgraded, not mozillasocket,lurnarsocket or shitsocket.
Then, sec-websocket-accept this is the server confirmed, and encrypted after the Sec-websocket-key. Server: OK, well, I know, show you my ID card to prove it.
Later, Sec-websocket-protocol is the protocol that represents the final use.

Now that HTTP has done all of its work, the next step is to follow the WebSocket protocol completely.  This is followed by the work of the WebSocket agreement. Three, Long poll and Ajax polling and WebSocket Principle 1, the principle of Ajax polling. The scenario is as follows:
Client: La LA, no new information (Request)
Service side: No (Response)
Client: La LA, no new information (Request)
Service side: No. (Response)
Client: La LA, no new information (Request)
Service side: Hello annoying ah, no AH. (Response)
Client: La LA, there are no new messages (Request)
Server: All right, all right, here you are. (Response)
Client: La LA, there are no new messages (Request)
Service side: ... Didn't.... Didn't... There is no principle of (Response)----Loop 2, long poll.
Long poll in fact, the principle of Ajax polling is similar, is the use of polling, but to take a blocking model (always call, do not receive the phone), that is, after the client initiates the connection, if there is no message, it has not returned response to the client. Until a message is returned, the client establishes a connection again and again after the return is completed.
The scenario is as follows:
Client: La La la, there is no new information, no words to wait for it to return to me (Request)
Service side: Amount. (wait until there is a message). Here you Go (Response)
Client: La La la, there is no new information, no words to wait for the return to Me (Request)-loop
From the above can be seen in fact, these two ways, are constantly establishing an HTTP connection, and then wait for service-side processing, can reflect another feature of the HTTP protocol, Passive Nature
What is passive, in fact, the server can not actively contact the client, can only be initiated by the client.
Simply put, the server is a very lazy refrigerator (it is a stem) (not, not the initiative to initiate the connection), but the boss has orders, if there are customers, no matter how tired should be well received.
After that, let's talk about the flaws.
It's easy to see from above, however, that both of these are very resource-intensive.
Ajax polling requires the server to have fast processing speed and resources. Speed
Long poll need to be very high concurrency, that is, the ability to receive customers at the same time. (Venue size)
So Ajax polling and long poll are likely to happen.

client: La la la, do you have any new information?
Service side: The monthly line is busy, please try again later (503 Server unavailable)
client: .... All right, cheer up, do you have any new information?
Service side: The monthly line is busy, please try again later (503 Server unavailable)

Client: <img src= "https://pic1.zhimg.com/7c0cf075c7ee4cc6cf52f4572a4c1c10_b.jpg" data-rawwidth= "143" data-rawheight= "class=" Content_image "width=" 143 ">
then the service side is busy dying: refrigerator, I want more refrigerators! More.. More.. 3, the principle of websocket.
From the above example, we can see that neither of these approaches is the best way and requires a lot of resources.
A need for faster speed, a need for more ' phone '. Both of these will lead to higher demand for ' phones '.
Oh yes, forget to say HTTP is still a stateful protocol.
The popular saying is that the server because of the daily to receive too many customers, is a Forgetful Ghost, as soon as you hang up, he forgets all your things and loses all of your stuff. You'll have to tell the server again the second time.

So in this case, WebSocket appeared.
He solves these problems with HTTP.
First of all Passive Nature, when the server completes the Protocol upgrade (Http->websocket), the service side can actively push the information to the client.
So the above scenario can be modified as follows.
Client: La LA, I want to set up the WebSocket protocol, required services: Chat,websocket protocol version: + (HTTP Request)
Server: OK, confirm, upgrade to WebSocket protocol (HTTP protocols switched)
Client: Please push it to me when you have information.
Server: OK, sometimes I will tell you.
Service side: Balabalabalabala
Service side: Balabalabalabala
Service side: ha haha haha ah haha haha
Service side: Laughing at me ha ha haha haha

That's what it's all about, just going through HTTP request one time, we can do a steady stream of information transmission. (in programming, this design is called a callback, that is: you have the information to notify me again, and not my stupid every time to ask you)
Such a protocol solves the situation where there is a delay in synchronization and is very resource intensive.
So why would he solve the problem of consuming resources on the server?
In fact, the program we use is going through two layers of proxy, that is, HTTP protocol in Nginx and other servers to resolveAnd then send it to the appropriate Handler (PHP, etc.)To deal with.
To put it simply, we have a very fast pick-up Line Clerk (Nginx), he was responsible for handing over the question to the appropriate Customer Service (Handler)
Itself operator basically the speed is enough, but every time it's stuck in Customer Service (Handler), old. Customer ServiceProcessing speed is too slow. , resulting in insufficient customer service.
WebSocket solves such a problem, after the establishment, can directly with the operator to establish Long Connection, when there is information, customer service find ways to inform the operator, then operatorIn a unified transfer to the customer.
This will solve the problem of customer service processing speed too slow.

At the same time, in the traditional way, to continue to build, close the HTTP protocol, because the HTTP is non-stateful, every time to re-transmitting identity info (authentication information)To tell the server who you are.
Although the operator is very fast, but every time to listen to such a pile, efficiency will be reduced, but also have to constantly transfer this information to customer service, not only waste customer service Processing Timeand consumes it in network transmissions. excessive traffic/time.
But websocket only needs an HTTP handshake, so that the entire communication process is established in a single connection/state, and avoids the non-state of HTTP, the server will always know your information until you close the request, so that the operator to resolve the HTTP protocol repeatedly, but also to see the identity info information.
At the same time by Customer Unsolicited Inquiry, converted to the server (push) when there is information to send (of course, the client is still waiting to send the message over. ), when no information is given to the operator (Nginx), do not need to occupy their own speed is slow Customer Service (Handler)The
--------------------
As for how to use WebSocket on clients that do not support websocket. The answer is: can't
But you can do this by saying long poll and Ajax polling. simulate a similar effect

The principle of websocket, and the relationship with HTTP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.