First, WebSocket Overview |
The WebSocket protocol is based on the TCP protocol, not the HTTP protocol.
As follows:
ws://127.0.0.1 or wss://127.0.0.1 is the websocket request.
Note: ws represents WebSocket protocol, WSS represents an encrypted WebSocket agreement.
The advantage of WebSocket is to allow the server and customer service to communicate with each other in real-time, and unlike Ajax, only by the customer service to initiate the request, and WebSocket is not subject to the same-origin policy restrictions, this is precisely the weakness of Ajax.
Well, after a preliminary understanding of WebSocket, we will explore the implementation of a demo together step-by-step.
Second, the Customer service side tour |
Because it is based on WebSocket, that at the customer service side, first, you have to initiate a websocket request.
As follows:
<!DOCTYPE HTML> <Head> <title>WebSocket</title> </Head> <Body> <Script> //Create a WebSocket object request varSocket= NewWebSocket ('ws://127.0.0.1:8080/'); </Script> </Body></HTML>
Entirecode
Secondly, the callback function is used to listen to the corresponding event and deal with it. There are altogether four monitoring events:
1. Onpen: triggered when the request succeeds
2. OnClose: triggered when the request is closed
3. onerror: triggered when an error occurs during a request or connection
4. onMessage: triggered when a message is sent by the receiving server
also, when a request is sent, the WebSocket instance that is created has a status value of readystate:
1. 0: The representative is not connected or is connected;
2. 1: the representative connection succeeds;
3. 2: The delegate is closing the connection;
4. 3: on behalf of the connection is closed.
We added these four listener events to the demo.
As follows:
<!DOCTYPE HTML> <Head> <title>WebSocket</title> </Head> <Body> <Script> //Create a WebSocket object request varSocket= NewWebSocket ('ws://127.0.0.1:8080/'); //corresponding Listener EventsSocket.onopen=OnOpen; Socket.onclose=OnClose; Socket.onerror=OnError; Socket.onmessage=OnMessage; </Script> </Body></HTML>
Entirecode
In this listener event, you can add a trigger function as you wish.
As follows:
<!DOCTYPE HTML> <Head> <title>WebSocket</title> </Head> <Body> <Script> varOnOpen= function(event) {Console.log ('Socket opened. ReadyState:'+socket.readystate); varmsg={type:"message", Text:"something", ID:" Number", Time:Date.now ()}; //Send can send a string, blob, or Arraybuffer to the background, serializing it with JSON when the object is passed insocket.send (Json.stringify (msg)); }; varOnClose= function(event) {Console.log ('Socket closed.readystate:'+socket.readystate); Console.log ('Connected to:' +Event.currentTarget.url); }; varOnMessage= function(data) {Console.log ("We Get signal:"); Console.log (data); Console.log ('Onmessageready:' +socket.readystate); }; varOnError= function(event) {Console.log ("We got an error.:" +event.data); }; varSocket= NewWebSocket ('ws://127.0.0.1:8080/'); Socket.onopen=OnOpen; Socket.onclose=OnClose; Socket.onerror=OnError; Socket.onmessage=OnMessage; </Script> </Body></HTML>
Entirecode
Third, node create server |
Create a simple server with node to see the entire websocket process.
Because it is the WebSocket protocol, you need to introduce a WS module in node, assuming we are listening on a port number of 8080.
As follows:
// WS module Required var Websocketserver = require (' ws '). Server; // and create a WSS server var New Websocketserver ({port:8080});
Entirecode
then we need to send a little something to the customer service after the connection is successful, such as ' Hello World ', as well as the event message when the insofar server sends the message.
As follows:
// WS module Required var Websocketserver = require (' ws '). Server; var New Websocketserver ({port:8080}); Wss.on (function(WS) { ws.on (function (message) { var obj = json.parse (message); Console.log (' Received:%s ', obj.time); }); Ws.send (' Hello World '); Console.log (' running!! ');
Entirecode
Prerequisite: because the WS module is introduced, the WS module needs to be introduced: NPM install WS
First, run node's simple server (I'll store it in D:websocket/server.js).
As follows:
Next, run the client side code and open the Chrome debugger:
Look at the node environment just now, the following:
They can already communicate with each other.
Let's Open the Chrome debugger and look at the WebSocket request as follows:
in Requestheaders , "Connection:upgrade" indicates that the browser notifies the server if it can upgrade to the WebSocket protocol. Origin is used to verify that the browser domain name is within the scope of the server license. The Sec-websocket-key is used for the Handshake Protocol Key, which is a base64 encoded 16-byte random string. The upgrade header information indicates that the communication protocol has been shifted from http/1.1 to the protocol specified by the item.
in Responseheaders , "Connection:upgrade" notifies the browser that the protocol needs to be changed. Sec-websocket-accept is the server that adds a "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" string after the Sec-websocket-key string provided by the browser, Then take the Sha-1 hash value. The browser validates this value to prove that the target server is actually responding to the WebSocket request.
[1] Ruan Yi Feng, WebSocket
[2] divID Walsh,websocket and Socket.io
[3] Socket.io
[4] Writing WebSocket client applications
[5] Websockets:a Guide
With node combat websocket