Building a live web using WebSocket

Source: Internet
Author: User

In order to prevent unscrupulous site crawler crawling articles, hereby identified, reproduced please indicate the source of the article. LAPLACEDEMON/SJQ.

Http://www.cnblogs.com/shijiaqi1066/p/3795075.html

1 WebSocket and traditional web real-time communication technology

1.1 WebSocket

HTTP is a typical single-work mode. This is the Request/response-based approach to interacting with the server. HTML5 provides a duplex communication protocol websocket between the browser and the server.

1.2 Traditional Web real-time communication technology

    • Polling
    • Comet
    • Long polling
    • Flash XML Socket

Polling, the server pressure is large, real-time poor, inefficient.

The mobile side has very poor support for Flash.

Comet and long polling should be the best technology for Web real-time interaction in traditional scenarios. The essence of these two technologies is a kind of hack technology. Comet has many drawbacks compared to long polling. But this does not affect their application in the traditional real-time web. The biggest problem with these two technologies is that each interaction has too many headers for the HTTP packet, and the actual meaningful information may be small, resulting in very low network utilization.

In the case of long polling, the server pressure will be greater because of the request/Response mode.

2 WebSocket Protocol

Both the WebSocket and HTTP protocols are TCP-based and are reliable protocols. The WebSocket and HTTP protocols belong to the Application layer protocol. The websocket uses standard 80 and 443 ports, both of which are friendly ports on the firewall and do not require firewall permission.

The format of the WebSocket protocol is "ws://ip:port" or "wss://ip:port". Where WSS represents the WebSocket protocol for encrypted transmissions.

The WebSocket protocol requires a "handshake". This "handshake" phase is done through the HTTP protocol, the "handshake" behavior through the Request/response header, only need to exchange very little data, you can create a duplex channel based on the TCP/IP protocol.

The figure is referenced from http://blog.sina.com.cn/s/blog_acddf95d0101beuj.html

The browser establishes a connection with the server through a TCP three handshake, and if the connection fails, the browser receives an error message notification.

After TCP establishes the connection successfully, the browser transmits the WebSocket supported version number through the HTTP protocol, the Word version number of the Protocol, the original address, the host address and so on some column fields to the server side.

2.1 WebSocket Handshake

The WebSocket Protocol handshake protocol is very simple.

Example: Run the WebSocket Echo sample program provided by TOMCAT7. When connect occurs, the information is intercepted in Chrome. and the packets obtained in the Intercept tool.

As shown in Chrome

The truncation tool shows

Request message

Description

Connection:upgrade and Upgrade:websocket indicate that this request is to perform a WebSocket handshake action.

The Sec-websocket-version header value that represents the WebSocket version information supported by the browser.

The value of the Sec-websocket-key header is a randomly generated string by the client.

Response message

Description

The value of sec-websocket-accept in the handshake information of the server response is the result of the server being evaluated and encrypted by the value of the Sec-websocket-key of the client header.

The server's response status is 101, indicating that the server side has understood the client's requirements, and that the client needs to switch to the new protocol to complete subsequent communication based on the protocol type in upgrade.

The TCP/IP duplex channel based on WebSocket has been established after the communication with the reported text.

2.2 Handshake verification

The oldest WebSocket draft standard is no security key. There are two security keys in draft 7.5 and 7.6. There is only one security key in draft 10.

The "Sec-websocket-key1" and "Sec-websocket-key2" in HTTP headers in 7.5, 7.6 are merged in 10 for a "Sec-websocket-key". The value of upgrade in the HTTP header is modified by "WebSocket" for "WebSocket". The "-origin" in the HTTP header is modified for "Sec-websocket-origin".

Added HTTP Header "Sec-websocket-accept", used to return the original draft 7.5, 7.6 The server returned to the client handshake verification, the original is returned in the form of content, is now placed in the HTTP header.

The way server generates validation varies greatly.

Old version WebSocket

The previous version generates tokens in the following ways:

Take out all the numeric characters in the Sec-websocket-key1 to form a number, here is 1427964708, then divide by the number of spaces in the Key1, get a value, retain the value of the integer digits, get the value N1 ; Take the same algorithm for Sec-websocket-key2, get the second integer N2, connect N1 and N2 in Big-endian character sequence, and then connect with another Key3 to get a primitive sequence ser_key. Key3 refers to the handshake request at the end, there is a 8-byte strange string ";" ###### ", this is Key3. The Ser_key is then MD5 to a 16-byte long Digest, which is the token required for the old version of the protocol, and then the token is appended to the handshake message and sent back to the client to complete the handshake.

New WebSocket

The new token generation method is as follows:

First the server intercepts the key (length 24), such as 4tajitqo9so2wu8lkrsq3w==, and uses it and a custom string (length of 258EAFA5-E914-47DA-95CA-C5AB0DC85B11) to connect. Then the string is SHA-1 algorithm encryption, get the length of 20 bytes of binary data, and then the data is BASE64 encoded, the end of the service side of the key, that is Ser_key. The handshake succeeded after the server attached Ser_key to the return value sec-websocket-accept.

2.3 Data Message Format

The old version of the protocol is relatively simple, simply add a ' \x00′ before the original data, add a ' \xff ' on the last side, that is, if the client sends a string ' test ', the WebSocket server actually receives the data: ' X00test\ XFF ', so you just have to peel off the two characters.

The new version of the agreement on this part of the rules are more complex, the following is the format of the standard: (in Firefox may be confused, please change chrome)

The Fin:1 bit, which is used to indicate that this is the last message fragment of a message, of course the first message fragment may also be the last message fragment;

RSV1, RSV2, RSV3: are 1, respectively, if there is no agreement between the two sides of the custom protocol, then these values must be 0, otherwise must be broken websocket connection;

Opcode:4 bit operation code, define payload data, if you receive an unknown opcode, the connection must also be broken, the following is the definition of the opcode:

%x0 represents a continuous message fragment

%X1 represents a text message fragment

%X2 table not in binary message fragment

%x3-7 operation code reserved for future non-control message fragments

%X8 indicates the connection is closed

%X9 indicates a ping for heartbeat check

%xa indicates the pong of the heartbeat test.

%xb-f retention opcode for future control message fragments

Mask:1 bits, defines whether the transmitted data is masked, if set to 1, the mask key must be placed in the Masking-key area, the client sends all messages to the server, the value of this bit is 1;

Payload Length: The amount of data transmitted in bytes: 7-bit, 7+16-bit, or 7+64-bit. If the value is 0-125 in bytes, that value represents the length of the transmitted data, and if the value is 126, then the two bytes represent a 16-binary unsigned number that represents the length of the transmitted data, and if the value is 127, The following is a 64-bit non-conforming number represented by 8 bytes, which is used to represent the length of the transmitted data. The number of multibyte lengths is expressed in the order of the network bytes. The length of the load data is the sum of the extended data and the application data, the length of the extended data may be 0, so the length of the payload data is the length of the applied data.

masking-key:0 or 4 bytes, the data sent by the client to the server is masked by an embedded 32-bit value, and the mask key exists only when the mask bit is set to 1. Payload data: (x+y) bit, the load is the sum of the extended data and the length of the application data. Extension data:x bit, if there is no special convention between the client and the server, the extended data is always 0 length, and any extension must specify the length of the extended data, or how long the length is calculated, and how the correct handshake is determined when the handshake occurs. If there is extended data, the extended data is included within the length of the payload data. Application Data:y bit, arbitrary application data, after extending the data, the length of the applied data = the length of the payload data-the length of the extended data.

2.4 WebSocket version and browser support

form from: Http://zh.wikipedia.org/wiki/WebSocket

3 web front-end related WebSocket

3.1. API definition

WebSocket API is illegal and simple, the following is the definition of the

Enum Binarytype {"blob", "Arraybuffer"}; [Constructor (domstring URL, optional (domstring or domstring[]) protocols)]interface Websocket:eventtarget {readonly A  Ttribute domstring URL;  Ready State const unsigned short connecting = 0;  Const unsigned short OPEN = 1;  Const unsigned short CLOSING = 2; Const unsigned short CLOSED = 3;
ReadOnly attribute unsigned short readyState; ReadOnly attribute unsigned long bufferedamount; Networking attribute EventHandler OnOpen; Attribute EventHandler onerror; Attribute EventHandler OnClose; readonly attribute domstring extensions; ReadOnly attribute domstring Protocol; void Close ([Clamp] optional unsigned shortcode, optional domstring reason); Messaging attribute EventHandler onmessage; Attribute Binarytype Binarytype; void Send (domstring data); void Send (Blob data); void Send (ArrayBuffer data); Voidsend (Arraybufferview data);};

3.2 Simple examples of practical use

Example 1

varWSServer = ' Ws://localhost:8888/demo ';varWebSocket =NewWebSocket (wsserver); Websocket.onopen=function(evt) {onOpen (evt)};websocket.onclose=function(evt) {onClose (evt)};websocket.onmessage=function(evt) {onMessage (evt)};websocket.onerror=function(evt) {onError (evt)};functionOnOpen (evt) {Console.log ("Connected to WebSocket server.");}functionOnClose (evt) {Console.log ("Disconnected");}functionOnMessage (evt) {Console.log (' Retrieved data from server: ' +evt.data);}functionOnError (evt) {Console.log (' Error occured: ' +evt.data);}

Example 2

<! DOCTYPE html><meta charset= "Utf-8"/><title>websocket test</title><script language= " JavaScript "type=" Text/javascript ">varWsuri = "ws://echo.websocket.org/"; varoutput;
functioninit () {Output= document.getElementById ("Output"); Testwebsocket (); } functionTestwebsocket () {WebSocket=NewWebSocket (Wsuri); Websocket.onopen=function(evt) {OnOpen (evt)};
Websocket.onclose=function(evt) {onClose (evt)}; Websocket.onmessage=function(evt) {onMessage (evt)}; Websocket.onerror=function(evt) {onError (evt)}; } functionOnOpen (evt) {Writetoscreen ("CONNECTED"); Dosend ("WebSocket Rocks"); } functionOnClose (evt) {Writetoscreen ("Disconnected"); } functionOnMessage (evt) {Writetoscreen (' <span style= ' color:blue; >response: ' + evt.data+ ' </span> '); Websocket.close (); } functionOnError (evt) {Writetoscreen (' <span style= ' color:red; >ERROR:</span> ' +evt.data); } functiondosend (message) {Writetoscreen ("SENT:" +message); Websocket.send (message); } functionwritetoscreen (message) {varPre = Document.createelement ("P"); Pre.style.wordWrap= "Break-word"; Pre.innerhtml=message; Output.appendchild (pre); } window.addeventlistener ("Load", init,false);</script>

Code Brief

Use new to create the WebSocket object.

var Wsuri = "ws://echo.websocket.org/";

WebSocket = new WebSocket (Wsuri);

The WebSocket object supports a total of four event response methods OnOpen, onmessage, onclose , and onerror. This will not block the UI and get a better user experience.

The OnOpen event is triggered when the browser and server connections are successful.

Websocket.onopen = function (evt) {};

If the connection fails, sending, receiving data fails, or handling data errors, the OnError event is triggered.

Websocket.onerror = function (evt) {};

The OnMessage event is triggered when the browser receives data sent from the server. The parameter evt contains the data transmitted by the server;

Websocket.onmessage = function (evt) {};

The OnClose event is triggered when the browser receives a close connection request sent by the server.

Websocket.onclose = function (evt) {};

The problem of heartbeat packs also needs to be considered in practical applications.

4 Disadvantages of the WebSocket

The biggest problem is browser compatibility issues. The low version of IE does not support this technology until IE10 begins to support WebSocket technology.

Of course, the solution is for a low-version browser to use Flash to emulate websocket.

such as: Web-socket-js Address: https://github.com/gimite/web-socket-js/

5 WebSocket of server implementations

WebSocket has many examples of implementations on the Web. The following is a list of server implementations that individuals will study.

    • Netty implementation
    • TOMCAT7 implementation
    • JAVAEE7+TOMCAT8 implementation
    • node. JS implementation

Resources

Http://zh.wikipedia.org/wiki/WebSocket

Http://www.web-tinker.com/search/websocket/1.html

http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/

http://hackecho.com/2012/04/new-hybi-10-protocol-of-websocket/

http://www.zendstudio.net/archives/web-socket-heartbeat-package/

In order to prevent unscrupulous site crawler crawling articles, hereby identified, reproduced please indicate the source of the article. LAPLACEDEMON/SJQ.

Http://www.cnblogs.com/shijiaqi1066/p/3795075.html

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.