Source Address: Https://github.com/Tinywan/PHP_Experience
first, detailed code case detailed interpretation of a simple HTML5 WebSocket JS example Tutorial, with the complete JavaScript websocket instance source code, as well as the example effect demo page, and the core code of this example in-depth interpretation. From the three stages of websocket communication (open handshake, data transfer, close handshake), the browser and server did something in each stage. Check if the browser supports WebSocket if (window. WebSocket) {console.log (' This browser supports WebSocket '); }else{Console.log (' This browser does not supports WebSocket '); Copy the Code<!DOCTYPE HTML> <MetaCharSet= "Utf-8" /> <title>WebSocket Test</title> <Scriptlanguage= "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> <H2>WebSocket Test</H2> <DivID= "Output"></Div> </HTML>Copy code Two, the main code interpretation: 1, the application of a WebSocket object parameter is the server-side address that needs to be connected, the same as the HTTP protocol uses/HTTP, the URL of the WebSocket protocol starts with ws://, Additionally the secure WebSocket protocol starts with wss://. var Wsuri = "ws://echo.websocket.org/"; websocket = new WebSocket (Wsuri); 2, WebSocket objects support four messages OnOpen, OnMessage, OnClose and onerror we can see that all actions are triggered by the message, so that the UI is not blocked, and the UI has a faster response time and a better user experience. (1) When the browser and Websocketserver connection is successful, the OnOpen message is triggered, Websocket.onopen = function (evt) {}, and (2) If the connection fails, the sending, receiving data fails, or the processing data is faulty, The browser will trigger the onerror message, Websocket.onerror = function (evt) {}, (3) The Websocketserver message is triggered when browser receives the data sent by OnMessage. The parameter evt contains data transmitted by the server, Websocket.onmessage = function (evt) {}, (4) When browser receives a close connection request sent by the Websocketserver side, The OnClose message is triggered. Websocket.onclose = function (evt) {};3, Communication protocol websocket and TCP, HTTP WebSocket are TCP-based, so they are reliable protocols that Web developers call W The Send function of Ebsocket is eventually transmitted through TCP's system interface in the implementation of browser. WebSocket and the HTTP protocol belong to the application layer protocol, so what is the relationship between them? The answer is yes, websocket. When a handshake connection is established, the data is transmitted over the HTTP protocol, but after the connection is established, The actual data transfer phase is not required to participate in the HTTP protocol. Third, WebSocket communication detailed interpretation: from can be seen clearly, divided into three stages: open handshake data transfer closed handshake shows the WebSocket mainThe three-step browser and the server side do the things separately. Four, the advantages of WebSocket a), the server and the client exchange between the header information is very small, about 2 bytes; b), the client and the server can actively transmit data to each other; c), create TCP requests and destroy requests without frequency, reduce the consumption of network bandwidth resources, but also save server resources; V. Establishing a connection handshake when the Web application calls the new WebSocket (URL) interface, browser begins the process of establishing a handshake connection with the Webserver address as a URL. 1. Browser with the WebSocket server through a TCP three handshake to establish a connection, if the connection fails, then the subsequent procedure will not be executed, the Web application will receive an error message notification. 2. After TCP establishes the connection successfully, BROWSER/UA 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. 3. After the WebSocket server receives the handshake request sent by Browser/ua, if the packet data and format are correct, the client and server side protocol version number matches, and so on, accepts this handshake connection, and gives the corresponding data reply, the same reply packet is also transmitted using HTTP protocol. 4. Browser received the server reply to the packet, if the packet content, format is not a problem, it means that the connection is successful, triggering the OnOpen message, the web developer can at this time through the send interface to the server to send data. Otherwise, the handshake connection fails, and the Web application receives the ONERROR message and knows why the connection failed. This handshake is much like HTTP, but it is not, it allows the server to interpret a portion of the handshake request in HTTP, and then switch to WebSocket VI, the data transmission Webscoket protocol, the transmission of the information in the form of a frame sequence. With data security in mind, the data frames that the client transmits to the server must be masked. If the server receives a data frame that has not been masked, it must actively close the connection. The data frames that the server transmits to the client must not be masked. If a client receives a masked data frame, it must actively close the connection. For the situation, the party that found the error can send a close frame to the other (the status code is 1002, which indicates a protocol error) to close the connection. Turn off WebSocket (handshake) using Wireshark to monitor the data above the WebSocket example. Copy Code get/http/1.1 upgrade:websocket connection:upgrade HOST:ECHO.WEBSOCket.org origin:null pragma:no-cache Cache-control:no-cache sec-websocket-key:qcgtb1rj6hceetrlpfux/a== Sec-WebSock Et-version:13 sec-websocket-extensions:x-webkit-deflate-frame Cookie: __utma= 9925811.951031439.1365242028.1365980711.1366068689.5; __utmc=9925811; __utmz=9925811.1365242028.1.1.utmcsr=websocket.org|utmccn= (Referral) |utmcmd=referral|utmcct=/HTTP/1.1 101 Web Socket Protocol handshake upgrade:websocket Connection:upgrade sec-websocket-accept:84qpane33qhxomcz8bgkfde1ahk= Se Rver:kaazing Gateway date:tue, Apr 09:51:25 GMT access-control-allow-origin:null Access-control-allow-creden Tials:true Access-control-allow-headers:content-type access-control-allow-headers:authorization Access-control-allow-headers:x-websocket-extensions access-control-allow-headers:x-websocket-version Access-control-allow-headers:x-websocket-protocol. a[j6>h. 8a/. {x%.0y.. WebSocket Rocks. I ..... Copy Code
--javascript Example of WebSocket combat