Understand the principle of Websocket

See a share almost known to reply, through the familiar and easy to understand without boring, no preacher parade, simply to share. In this paper, a content that is, finishing, do we do not think it should be a good point

I. websocket and http

  • WebSocket is something that comes out of HTML5, that is, the HTTP protocol does not change, or does not matter, but HTTP does not support persistent connections (long connections, loop connections are not counted)
  • First, HTTP 1.1 and 1, also known as keep-alive, the number of HTTP requests are merged into one, but Websocket is a new protocol, the HTTP protocol with the basic Never mind, just to shake hands with standard compatible with the existing browser only, that is to say it is a supplement to the HTTP protocol through such a map to understand
    Understand the principle of Websocket
  • There is intersection, but not all.
  • In addition, Html5 refers to a series of new API, or new specifications, new technologies. The Http protocol itself is only 1 and 1.1, and is not directly related to the Html itself.. In general, you can transfer non – Html data using the HTTP protocol, that is =. =
  • In simple terms, the hierarchy is different.

Two, Websocket is what kind of agreement, what are the advantages?

  • First, Websocket is a persistent protocol, as opposed to HTTP, a non persistent protocol. Simply, for example, explain the PHP life cycle, which is now widely used.
  • The life cycle of HTTP is defined by Request, that is, a Request, a Response, and in HTTP1.0, this HTTP request is over.
  • Improved in HTTP1.1 so that there is a keep-alive, that is, in a HTTP connection, you can send multiple Request and receive multiple Response. But remember, Request = Response, always in HTTP, that is, a request can have only one response. And this response is also passive, can not take the initiative to launch.

Coach, how much do you have to do with Websocket because you’ve had so much BB? (3: “angle) well, I was going to say Websocket..

  • First of all, Websocket is based on the HTTP protocol, or HTTP protocol is used to do part of the handshake.
  • Let’s look at a typical Websocket handshake (borrowed from Wikipedia’s.)
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com
  • Familiar with HTTP’s children’s shoes may have discovered, in this section similar to HTTP agreement handshake request, several things. I’ll explain the effect by the way.
Upgrade: websocket Connection: Upgrade
  • This is the core of Websocket, Apache and Nginx told the server: pay attention to you, I launched the Websocket protocol, hurry up and help me find the assistant not the old-fashioned processing corresponding to the HTTP.
Sec-WebSocket-Key:, x3JJHMbDL1EzLkh9GBhXDw==, Sec-WebSocket-Protocol:, chat, superchat, Sec-WebSocket-Version: 13
  • First of all, Sec-WebSocket-Key is a Base64 value of encode, the browser is randomly generated, tell the server: peat, do not fool the nest, I want to verify, is not really a Websocket assistant.
  • Then, Sec_WebSocket-Protocol is a user-defined string that identifies the protocols needed for different services under the same URL. Simple understanding: I’m going to serve A tonight, don’t make a mistake!
  • Finally, Sec-WebSocket-Version is used to tell the server Websocket (Draft protocol version), for the first time, the Websocket protocol in the Draft stage, all kinds of agreements have, and there are a lot of strange things in different period, what Firefox and Chrome are not using a version of the original Websocket protocol and the like, but too much of a big problem.. But now, have fixed a thing ~ ~ all use dehydration: Waiter, I want to be 13 years old, _, oh
  • The server then returns the following, indicating that the request has been accepted and that the Websocket is successfully established!
HTTP/1.1 101, Switching, Protocols, Upgrade:, websocket, Connection:, Upgrade, Sec-WebSocket-Accept:,, HSmrc0sMlYUkAGmm5OPpG2HaGWk=, Sec-WebSocket-Protocol:, chat
  • This is where the HTTP is finally responsible, and tell the client that I have successfully switched the agreement!
Upgrade: websocket Connection: Upgrade
  • Still fixed, tell the client that the Websocket protocol will be upgraded, not mozillasocket, lurnarsocket, or shitsocket.
  • Then, Sec-WebSocket-Accept is the Sec-WebSocket-Key that is confirmed by the server and encrypted. Server: all right, OK, I see. Show me my ID CARD to prove it..
  • The latter, Sec-WebSocket-Protocol, is the protocol for final use.
  • So far, HTTP has done all its work, and then it follows the Websocket protocol. The specific agreement is not explained here.

— — — part of technical analysis is complete — —

Understand the principle of Websocket

You TMD and BBB for so long, that in the end what the ghost of Websocket, HTTP, long, poll,
, or Ajax polling can not achieve real-time messaging it?.

Understand the principle of Websocket

Well done, young man, let’s talk about what Websocket works for. Here, give you some Hu (Su), mu (Dan), bu (red)

Understand the principle of Websocket

Three, the role of Websocket

  • Before speaking about Websocket, I was going to talk about the principles of long, poll, and Ajax polling. Ajax poll
  • The principle of Ajax polling is very simple, so that the browser sends a request every few seconds, asking whether the server has new information.

client: La La La, there is no new information (Request)
server: no client: La La La, there is no new information (Request)
server: no.. (Response)
client: La La, there is no new information (Request)
server: Hello, bored ah, no ah.. (Response)
client: La La, is there a new (Request)
server? OK, OK, here you are. (Response)
client: La La, is there a new message (Request)
server?:….. No…. No… No (Response) – – loop

Long poll
  • Long poll in principle with the Ajax polling are similar, the polling way, but take the blocking model (always call, did not receive not hanging up the phone), that is to say, the client initiates a connection, if no news has been returned to the client Response. The message does not return until the message is complete. After the return, the client creates the connection again and again.

Scene reproduction:
client: La La La, there is no new information, there is no, and so on, just return to me (Request)
server: amount.. Waiting for news to come.. Response
client: La La La, there is no new information, there is no, then wait until you have returned to me (Request) -loop

  • As can be seen above, in fact, these two methods are constantly building HTTP connections, and then waiting for server-side processing, can reflect another feature of the HTTP protocol, passivity.
  • What is passive, in fact, the server can not take the initiative to contact the client, only the client initiated.
  • To put it simply, the server is a very lazy refrigerator (it’s a terrier). (no, it can’t initiate the connection), but the boss has an order. If you have a client, no matter how tired you are, you should be well received.
  • With that, let’s talk about the flaws above. (forgive me for talking so much, OAQ)
  • It’s easy to see from above. Anyway, the above two are very resource consuming. Ajax polling requires the server to have quick processing speed and resources. (speed) long poll requires a high degree of concurrency, that is, the ability to receive customers simultaneously. (site size)
  • So both Ajax polling and long poll can happen. Client: la la la la, there is new information?
    server: the line is busy. Please try again later (503, Server, Unavailable)
    client:…. All right, La La, do you have any new information?
    server: the line is busy, please try again later (503, Server, Unavailable)
    client: then the server is busy on the side: refrigerator, I want more refrigerators! More。。 More。。 I was wrong.. This is the terrier again
Let us Websocket.
  • From the above example, we can see that the two methods are not the best way, and require a lot of resources. One needs faster speed, and one needs more phones. The demand for these two kinds of phones is getting higher and higher.
  • Oh, yes, forget to say HTTP is still a status protocol. Generally speaking, the server is a forgetful person because he receives too many clients every day. When you hang up the phone, he forgets all your things and loses all of your stuff. You have to tell the server again the second time.
  • So, in this case, Websocket appears. He solved these difficult problems of HTTP. First of all, passive, when the server has completed the protocol upgrade (HTTP-> Websocket), the server can take the initiative to push information to the client.

So the above scenario can be modified as follows.
client: La La La, I need to establish Websocket protocol services: chat, Websocket protocol version: 17 (HTTP Request)
server: OK, confirmation, has been upgraded to Websocket protocol (HTTP Protocols Switched)
client: when you have trouble information pushed to me oh..
server: OK, sometimes I’ll tell you.
server: balabalabalabala
server: balabalabalabala
server: ha ha ha ha ha ha ha
server: killing me ha ha ha ha ha ha ha

  • That’s what it takes. Once you’ve got a HTTP request, you can do a steady flow of information. (in the program design, this design is called callback, that you have the information again to inform me, I not stupid every time I run to ask you)
  • Such an agreement resolves the situation where synchronization is delayed and resources are consumed very much. So why does he solve the problem of resource depletion on the server?
  • In fact, we use the procedure is to go through two layers of agents, that is, HTTP protocol in the Nginx and other servers parsing, and then sent to the corresponding Handler (PHP, etc.) to deal with. To put it simply, we have a very fast Nginx who is responsible for passing the problem to the Handler.
  • The operator itself basically speed is enough, but always in the customer service (Handler), the old customer service processing speed is too slow. Customer service is not enough. Websocket has solved such a difficult problem. After setting up, it can establish a permanent connection with the operator directly. When there is information, the customer service will notify the operator, and then the operator will hand it over to the customer.
  • This will solve the problem of slow customer service processing.
  • At the same time, in the traditional way, it is necessary to constantly establish, close the HTTP protocol, because HTTP is non state, each time to re transmit identity info (identification information), to tell the server who you are.
  • Although the operator very fast, but each time to listen to such a pile, the efficiency will decline, while also constantly put these information to the customer service, customer service is not only a waste of time, but also in the networks consume too much traffic / time.
  • But Websocket only need a HTTP handshake, so that the entire communication process is based on a connection / state, it is to avoid the non state of HTTP, the server will always know your information, until you close the request, this would solve the operator to repeated analysis of the HTTP protocol, but also check the identity info information.
  • At the same time, by the customer’s initiative to ask, converted to the server (push) when there is information sent (of course, the client or other active information sent over) When you don’t have the information, give it to the operator (Nginx). You don’t need to slow your Handler at your own pace

– – – – –

As for how to use Websocket on a client that does not support Websocket.. The answer is: you can’t
, but you can simulate similar effects by polling long, poll, and ajax

– – – – –