After reading to let you thoroughly understand the WebSocket principle, with complete combat code (including front and back end)

Source: Internet
Author: User
Tags base64 encode

1. Preface

Recently a classmate asked me if I have done online consulting function. At the same time, the company just let me take over an IM project. So take the time today to record what you've learned recently. This article mainly analyzes the principle of WebSocket, and attaches a complete chat room combat Demo (including front and back end, code download link at the end of the text).

2, WebSocket and HTTP

The WebSocket agreement was born in 2008 and became an international standard in 2011. Now all browsers are supported. WebSocket's biggest feature is that the server can proactively push information to the client, the client can also proactively send information to the server, is a true two-way equality dialogue.

HTTP has 1.1 and 1.0 say, the so-called keep-alive, to merge multiple HTTP requests into one, but Websocket is actually a new protocol, and the HTTP protocol basically does not matter, just to be compatible with the existing browser, so in the handshake phase using the HTTP 。

The following diagram illustrates the main differences between HTTP and WebSocket:

Other features of WebSocket:

    • Based on the TCP protocol, the server-side implementation is relatively easy.
    • Good compatibility with HTTP protocol. The default port is also 80 and 443, and the handshake phase uses the HTTP protocol, so the handshake is not easy to block, through a variety of HTTP proxy server.
    • Data formats are lightweight, performance overhead is small, and communication is efficient.
    • You can send text, or you can send binary data.
    • Without the same origin limit, clients can communicate with any server.
    • The protocol identifier is WS (or WSS if encrypted) and the server URL is the URL.
3, WebSocket is what kind of agreement, concrete has 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 life cycle of HTTP is defined by the request, which is a request for a Response, and in HTTP1.0, the HTTP requests end.

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.

What does it have to do with WebSocket that you have so much BB? Well, I'm just going to say WebSocket.

First WebSocket is based on the HTTP protocol, or borrowing the HTTP protocol to complete a part of the handshake.

First, let's see a typical WebSocket handshake.

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.

Upgrade: websocketConnection: Upgrade

This is the core of WebSocket, tell Apache, Nginx and other servers: note, I initiated the request to use the WebSocket protocol, quickly help me find the corresponding assistant processing ~ rather than the 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 fool me, I want to verify that you are 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. 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's OK, it's settled. Everyone uses the same version: 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, 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.

4, the role of WebSocket

Before I talked about WebSocket, I went with the principle of Ajax polling and long poll.

4-1. 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:

客户端:啦啦啦,有没有新信息(Request)服务端:没有(Response)客户端:啦啦啦,有没有新信息(Request)服务端:没有。。(Response)客户端:啦啦啦,有没有新信息(Request)服务端:你好烦啊,没有啊。。(Response)客户端:啦啦啦,有没有新消息(Request)服务端:好啦好啦,有啦给你。(Response)客户端:啦啦啦,有没有新消息(Request)服务端:。。。。。没。。。。没。。。没有(Response) —- loop
4-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 initiated the request, if there is no message, will not return Response to the client. Until a message is returned, the client establishes a connection again and again after the return is completed.

Scene Reproduction:

客户端:啦啦啦,有没有新信息,没有的话就等有了才返回给我吧(Request)服务端:额。。 等待到有消息的时候。。来 给你(Response)客户端:啦啦啦,有没有新信息,没有的话就等有了才返回给我吧(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.

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. Long poll need to be very high concurrency, that is, the ability to receive customers at the same time.

So Ajax polling and long poll are likely to happen.

客户端:啦啦啦啦,有新信息么?服务端:正忙,请稍后再试(503 Server Unavailable)客户端:。。。。好吧,啦啦啦,有新信息么?服务端:正忙,请稍后再试(503 Server Unavailable)
4-3, WebSocket

From the above two examples, 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. 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 there is a WebSocket. 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.

客户端:啦啦啦,我要建立Websocket协议,需要的服务:chat,Websocket协议版本:17(HTTP Request)服务端:ok,确认,已升级为Websocket协议(HTTP Protocols Switched)客户端:麻烦你有信息的时候推送给我噢。。服务端:ok,有的时候会告诉你的。服务端:balabalabalabala服务端:balabalabalabala服务端:哈哈哈哈哈啊哈哈哈哈服务端:笑死我了哈哈哈哈哈哈哈

In this way, only a single HTTP request can be made to deliver a steady stream of information.

5. Actual Combat code

The update source for this article is hosted on GitHub

Reference Documentation:
PHP Socket Document
JS's WebSocket document

Front-end Code: HTTPS://GITHUB.COM/NNNGU/WEBSOCKETDEMO-JS
Back-end code: https://github.com/nnngu/WebSocketDemo-php

To run the steps:

    1. Open Directory in Terminal WebSocketDemo-php , executephp -q server.php
    2. Accessing WebSocketDemo-js the contents of a directory using a browserindex.html

Run:

After reading to let you thoroughly understand the WebSocket principle, with complete combat code (including front and back end)

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.