To see the WEB socket on the understanding of this article is really good, from the beginning to see the tail are very vivid, a breath of reading, no blur, very good

Source: Internet
Author: User
Tags base64 encode

https://www.zhihu.com/question/20215561/answer/40316953

On the understanding of this article is really good, from the beginning to see the tail are very vivid, a breath, no blur, very good, so recommend to everyone, is worth reading.

Ovear
Links: https://www.zhihu.com/question/20215561/answer/40316953
Source: Know
Copyright belongs to the author, please contact the author for authorization.

First, WebSocket is HTML5 out of the Thing (protocol), that is, the HTTP protocol does not change, or it is OK, but HTTP is not support for persistent connection (long connection, not counting the loop connection)
First HTTP has 1.1 and 1.0 said, that is, the so-called keep-alive, a number of HTTP requests to merge into one, but WebSocket is actually a new protocol, with the HTTP protocol is basically not related, just to be compatible with the existing browser handshake specification, that is, it is an HTTP protocol on a supplement can To understand through such a picture
There are intersections, but not all.
Another HTML5 refers to a series of new APIs, or new specifications, and new technologies. The HTTP protocol itself is only 1.0 and 1.1, and is not directly related to HTML itself.
In layman's terms, you can use HTTP ProtocolTransfer non-HTML Data, that's it. =
To put it simply, The hierarchy is different.

Second, WebSocket is what kind of agreement, concrete have what merit
First, WebSocket is a Persistence ofThe protocol, as opposed to HTTP, this Non-persistentAgreement.
Let's take a simple example and explain it in the PHP life cycle, which is widely used today.
1) The life cycle of HTTP is defined by the request, which is a request for a response, then in theHTTP1.0 in, this time the HTTP request is over.
Improvements have been made in HTTP1.1, which makes it possible to have a keep-alive, which means that in an HTTP connection, multiple request messages can be sent to receive multiple response.
But remember that request = Response, which is always the case in HTTP, which means that a request can have only one Response. And this response, too. Passive, and cannot be initiated on its own initiative.

coach, what do you have to do with websocket when you have so much BB?
_ (: З"∠) _ Well, I'm just going to say websocket.
First, WebSocket is based on the HTTP protocol, or borrowingAn HTTP protocol to complete a part of the handshake.
It's the same at the handshake stage.
-------The following professional technical content, do not want to see can skip lol:, or just look at the black content--------
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.
The specific agreement is not elaborated here.
------------------Technical Analysis section is complete------------------

You've been so damn websocket for so long, what the hell is the use of HTTP long poll, or Ajax polling can not be implemented real-time information delivery.


Well, young man, let's talk about WebSocket.
Here to get you some Hu (Sue) luo (dan) bu (red)
third, the role of WebSocket
Before I talk about WebSocket, I'll take a walk.Long PollAndAjax PollingThe principle.
The first is the Ajax polling, the principle of Ajax polling is very simple, so that the browser to send a request every few seconds, ask the server whether there is new information。
Scene Reproduction:
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... No (Response)----loop

Long poll
Long Poll In fact the principle is similar to Ajax polling, are the use of polling, but to take a blocking model (always call, not received on the phone), that is, after the client initiates the connection, if no message, 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.
Scene reproduction
Client: La La la, there is no new information, no words to wait for it to return to me (Request)
Service side: Amount. Wait till there's 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.

To finish this, let's talk about the above flaws (forgive me for so much nonsense Oaq)
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:
then the service side is busy dying: refrigerator, I want more refrigerators! More.. More.. (I was wrong.) This is the stem again. )

--------------------------
Well, let's just say 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, that's right.forget to say http or a stateless protocol 。 (Thank you for commenting that Oaq)
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
-----

To see the WEB socket on the understanding of this article is really good, from the beginning to see the tail are very vivid, a breath of reading, no blur, very good

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.