After reading, let you understand the WebSocket principle completely

Source: Internet
Author: User
Tags base64 encode

Accidentally in the know to see a reply, instantly feel like so many of the information before the reply so that I have a websocket deep understanding of the wood Has. So go to my blog and share. Prefer to read this kind of blog, reading it is easy, not boring, no preacher of the battle, purely for sharing. So much nonsense, and finally praise a ~

one, WebSocket and HTTP

WebSocket is the HTML5 (protocol), that is, the HTTP protocol does not change, or it does not matter, but HTTP is not support for persistent connection (long connection, not counting the loop Connection)

First of all, http has, 1.1 and 1.0 it is called keep-alive , to merge multiple HTTP requests into one, but in Websocket fact a new protocol, with the HTTP protocol basically does not matter, just to be compatible with the existing browser handshake specification, In other words, it is a supplement to the HTTP protocol that can be understood by such a graph.

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 transfer non-html data using the HTTP Protocol. =

In simple terms, 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.

The lifetime of the HTTP is defined by one, and Request Request in this case the Response HTTP1.0 http request ends.

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 keep Request = Response in mind that this 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, The WebSocket is based on the HTTP protocol, or the protocol that borrowed HTTP to complete a part of the Handshake.

First we 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 , and Nginx so on server: notice, I initiated is the WebSocket agreement, quickly help me 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 websocket Assistant.

then, Sec_WebSocket-Protocol A user-defined string is used to distinguish between the protocols that are required for different services under the same url. Easy to understand: tonight I have to service a, do not mistake

finally, to Sec-WebSocket-Version tell the server to use the Websocket Draft (protocol version), at the initial time, the WebSocket protocol is still in the Draft stage, all kinds of bizarre protocols have, and there are many strange things in the period, What Firefox and Chrome use 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 protocol is about to be upgraded Websocket , not mozillasocket,lurnarsocket or shitsocket.

then, Sec-WebSocket-Accept This is confirmed by the server, and after the encryption Sec-WebSocket-Key . Server: ok, ok, i'll show you my ID card to prove it.

later, the Sec-WebSocket-Protocol protocol that represents the End-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 are you going to do with that, http long poll or ajax轮询 not all of them can deliver real-time information?

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 speak websocket, I go with long poll ajax轮询 the principle of speaking and.

Ajax polling

The principle of Ajax polling is very simple, allowing the browser to send a request every few seconds, asking the server if there is any 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 pollIn fact, the principle is ajax轮询 similar, is the use of polling, but the blocking model is taken (always call, not received on 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 have very high concurrency, that is, the ability to host customers at the same time. (venue Size)

So ajax轮询 and long poll all of this could 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 stateful protocol.

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. He solves these problems with HTTP. first, the passivity, when the server completes the protocol upgrade (http->websocket), the service side can proactively push the message 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

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. To put it simply, we have a very fast one 接线员(Nginx) and he is responsible for handing over the questions to the corresponding 客服(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 solves such a problem, after the establishment, can directly with the operator to establish a persistent 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 constantly build, close the HTTP protocol, because the HTTP is non-stateful, each time to Re-transfer 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 heap, the efficiency will be reduced, but also have to constantly transfer this information to customer service, not only waste customer service processing time, but also in the network transmission consumes excessive traffic/time.

But websocket only need an HTTP handshake, so that the entire communication process is established in a connection/state, also 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, Also view information for identity Info.

At the same time by the customer unsolicited inquiry, the conversion to the server (push) has information when it is sent (of course, the client is still waiting to send the message over the active). ), when no information is given to the operator (Nginx), do not need to occupy their own slow speed of customer service (Handler)

——————–

As for how to use WebSocket on clients that do not support websocket. The Answer Is: No

But you can long poll ajax 轮询 simulate a similar effect by saying and.

After reading, let you understand the WebSocket principle completely

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.