WebSocket's Understanding & applications & Scenarios

Source: Internet
Author: User
Tags base64 encode

Ovear
Links: https://www.zhihu.com/question/20215561/answer/40316953
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

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 persistent protocol, relative to HTTP, a non-persistent protocol.
Let's take a simple example and explain it in the PHP life cycle, which is widely used today.
1) The HTTP lifecycle is defined by the request, which is a request for a response, and in HTTP1.0 the HTTP requests are ended.
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 is also passive , can not initiate.

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 of all, Sec-websocket-key is a Base64 encode value, this is the browser randomly generated, tell the server: peat, do not confuse the nest, I want to verify that Nikki is not really a 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. Easy to understand: tonight I have to service A, do not mistake
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 ~ everyone uses a thing ~ dehydration: Waiter, I want to be 13 years 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, OK, I'll 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 long poll and Ajax polling 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 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.
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 server processing, can reflect the HTTP protocol another feature, passivity .
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 yes, forget to say HTTP is still a stateless protocol. (Thank you for commenting that Oaq)
Popular saying is that the server because every day to receive too many customers, is a forgetful ghost , you hang up the phone, he put your things all forgotten, put all your things lost. You'll have to tell the server again the second time.

So in this case, WebSocket appeared. The
he solves these problems with HTTP.
First, passive , 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.
Server side: Balabalabalabala
Server: Balabalabalabala
server: ha ha ha haha ah haha haha
service side: Laughing at me ha haha haha haha

It becomes so that only one HTTP request , you 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, we use the program is to go through two layers of proxy, that is, HTTP protocol in Nginx and other servers , and then sent to the corresponding Handler (PHP, etc.) to deal with.
In short, we have a very fast line-up (Nginx), he is responsible for the issue to the corresponding customer service (Handler).
The operator itself is basically the speed is enough , but each time is stuck in customer service (Handler) , the old customer service processing speed is too slow. , resulting in insufficient customer service.
WebSocket solved such a problem, after the establishment, can directly with the operator to establish long-lasting connection , there is information when customer service to find ways to inform the operator, and then the operator in the 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

WebSocket's Understanding & applications & Scenarios

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.