JavaScript websocket Technical detailed _javascript skills

Source: Internet
Author: User

Overview

HTTP protocol is a stateless protocol, the server side itself does not have the ability to identify clients, must use external mechanisms, such as session and cookies, to maintain a dialogue with a specific client. This is more or less inconvenient, especially in the context of server-side and client needs to continuously exchange data (such as network chat). To solve this problem, HTML5 proposed the browser's WebSocket API.

The primary role of WebSocket is to allow full duplex (Full-duplex) communication between the server side and the client. For example, the HTTP protocol is a bit like emailing, which must wait for the other to reply; WebSocket is like making a phone call, the server side and the client can send data to each other at the same time, there is a continuous open data channel between them.

The WebSocket protocol can be used instead of Ajax methods to send text and binary data to the server, and there is no "same domain restriction".

Instead of using the HTTP protocol, WebSocket uses its own protocol. The WebSocket request made by the browser resembles the following:

get/http/1.1
Connection:upgrade
Upgrade:websocket
Host:example.com
Origin:null
sec-websocket-key:sn9crrp/n9ndmgdcy2vjfq==
Sec-websocket-version:13
The header information above shows that there is an HTTP header that is upgrade. The HTTP1.1 agreement stipulates that the upgrade header information indicates that the communication protocol is diverted from the http/1.1 to the protocol specified by the item. "Connection:upgrade" means that the browser notifies the server and, if it can, upgrades to the WebSocket protocol. Origin is used to verify that the browser domain name is within the scope of the server license. Sec-websocket-key is the key for the handshake protocol and is a base64 encoded 16-byte random string.

The server-side websocket response is

http/1.1 Switching protocols
Connection:upgrade
Upgrade:websocket
sec-websocket-accept:ffboob7fakllxgrsz0bt3v4hq5s=
Sec-websocket-origin:null
sec-websocket-location:ws://example.com/

The server side also uses "Connection:upgrade" to notify the browser and needs to change the protocol. Sec-websocket-accept is the server, after the Sec-websocket-key string provided by the browser, adds a "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" string, And then take the hash value of the sha-1. This value is validated by the browser to prove that the target server did respond to the websocket request. Sec-websocket-location represents the WebSocket URL for the communication.

Please note that the WebSocket protocol is represented by WS. In addition, there is the WSS protocol, which represents the encrypted WebSocket protocol, corresponding to the HTTPS protocol.
After the handshake is complete, the WebSocket protocol begins to transmit data on top of the TCP protocol.

WebSocket protocol requires server support, the current more popular implementation is based on Node.js Socket.io, more implementations can refer to the Wikipedia. As for browsers, the current mainstream browsers support the WebSocket protocol (including IE 10+), with the exception of the Opera Mini and Android Browser on the phone.

Client

The browser-side deal with the WebSocket protocol is nothing more than three things:

Establish a connection and disconnect
Sending data and receiving data
Handling Errors

Establish a connection and disconnect

First, the client checks whether the browser supports WebSocket by looking at whether the Window object has a WebSocket property.

if (window. WebSocket!= undefined) {

 //WebSocket code

}

Then, start a connection to the server (this assumes that the server is the 1740 port on this machine and that you need to use the WS protocol).

if (window. WebSocket!= undefined) {

 var connection = new WebSocket (' ws://localhost:1740 ');

}

After the connection is established, the WebSocket instance object (that is, the connection in the code above) has a ReadyState property that represents the current state and can take 4 values:

0: Connecting
1: Connection Success
2: Shutting down
3: Connection Close
After the handshake is successful, the readystate changes from 0 to 1 and triggers the Open event, where the message can be sent to the server. We can specify the callback function for the Open event.

Connection.onopen = Wsopen;

function Wsopen (event) { 
console.log (' Connected to: ' + Event.currentTarget.URL); 
}

Closing the WebSocket connection triggers the Close event.

Connection.onclose = Wsclose;

function Wsclose () { 
console.log ("Closed"); 
}

Connection.close ();

Sending data and receiving data

After the connection is established, the client sends data to the server via the Send method.

Connection.send (message);
in addition to sending a string, binary data can be sent using a Blob or Arraybuffer object.

Use Arraybuffer to send canvas image data

var img = canvas_context.getimagedata (0, 0,);

var binary = new Uint8array (img.data.length);

for (var i = 0; i < img.data.length i++) {

 binary[i] = Img.data[i];

}

Connection.send (binary.buffer);
Use BLOB to send file 
var file = document.queryselector (' input[type= ' file '] '). Files[0]; 
Connection.send (file);

The client receives data sent by the server that triggers the message event. You can handle the data returned by the server by defining the callback function for the message event.

Connection.onmessage = Wsmessage;

function Wsmessage (event) { 
console.log (event.data); 
}

The callback function for the above code, Wsmessage, is an event object with the Data property of the object that contains the information returned by the server.

If you receive binary data, you need to set the connection object to a BLOB or arraybuffer format.

Connection.binarytype = ' Arraybuffer ';

Connection.onmessage = function (e) {
 console.log (e.data.bytelength);//Arraybuffer object has bytelength attribute
};

Handling Errors

If an error occurs, the browser triggers an error event for the WebSocket instance object.

Connection.onerror = Wserror;

function Wserror (event) { 
Console.log ("Error:" + event.data); 
}

Server-side

The server side needs to deploy the code that handles websocket separately. Below, use Node.js to build a server environment.

var http = require (' http ');

var server = Http.createserver (function (request, response) {});

Suppose you are listening on port 1740.

Server.listen (1740, function () {

 console.log (new Date ()) + ' Server is listening on port 1740 ');



Then start the WebSocket server. This requires loading the WebSocket library, which, if not installed, can be installed using the NPM command first.

var websocketserver = require (' WebSocket '). Server;

var wsserver = new Websocketserver ({

 httpserver:server

});

The WebSocket server establishes a callback function for the request event.

var connection;
Wsserver.on (' request ', function (req) {

Connection = req.accept (' Echo-protocol ', req.origin); 
});

The callback function of the code above accepts a parameter req representing the request object. Then, within the callback function, establish the WebSocket connection connection. Next, you will specify a callback function for the connection message event.

 Wsserver.on (' request ', function (r) {connection = req.accept (' Echo-protocol ', req.origin

); 
<span class= "NX" >connection</span><span class= "P" >.</span><span class= "NX" >on</ Span><span class= "P" > (</span><span class= "S1" > ' message ' </span><span class= "P"; </span> <span class= "kd" >function</span><span class= "P" > (</span><span class= "NX" >message</span><span class= "P" >) </span> <span class= "P" >{</span> <span class= " KD ">var</span> <span class=" NX ">msgString</span> <span class=" O ">=</span> <span Class= "NX" >message</span><span class= "P" >.</span><span class= "NX" >utf8Data</span ><span class= "P" >;</span> <span class= "NX" >connection</span><span class= "P" >.< /span><span class= "NX" >sendutf</span><span class= "P" > (</span><span class= "NX" > Msgstring</span><span class= "P" >);</span> <span class= "P"}); </span&Gt

 });

Finally, monitor the user's disconnect events.

Connection.on (' Close ', function (Reasoncode, description) {

 Console.log (connection.remoteaddress + ' disconnected .');

});

Using the WS module, it is easy to deploy a simple WebSocket server.

var websocketserver = require (' ws '). Server;
var wss = new Websocketserver ({port:8080});

Wss.on (' connection ', function connection (WS) {
 ws.on (' message ', function incoming (message) {
 Console.log (' Received:%s ', message);

 Ws.send (' something ');
};

Socket.io Introduction

Socket.io is currently the most popular WebSocket implementation, including server and client two parts. Not only does it simplify the interface, it makes it easier to operate, but for browsers that do not support websocket, it automatically drops to Ajax connections to maximize compatibility. Its goal is to unify the communication mechanism so that all browsers and mobile devices can communicate in real time.

The first step is to install the Socket.io module in the server-side project root directory.

$ NPM Install Socket.io

The second step is to create the app.js in the root directory and write the following code (assuming the Express framework is used).

var app = require (' Express ') ();
var server = require (' http '). Createserver (app);
var io = require (' Socket.io '). Listen (server);

Server.listen ();

App.get ('/', function (req, res) {
 res.sendfile (__dirname + '/index.html ');
});

The code above indicates that the HTTP server is built and run first. The Socket.io runs on top of the HTTP server.

in the third step, insert Socket.io into the client Web page.

<script src= "/socket.io/socket.io.js" ></script>

Then, in client script, establish the WebSocket connection.

var socket = io.connect (' http://localhost:80 ');

Because this example assumes that the WebSocket host is the same machine as the client, the parameters of the Connect method are http://localhost. Next, specify the callback function for the news event, which is the server-side send news.

Socket.on (' News ', function (data) {
 console.log (data);
});

Finally, the emit method is used to send signals to the server to trigger the Anothernews event on the server side.

Socket.emit (' anothernews ');

Note that the emit method can replace the AJAX request, and the callback function specified by the on method is equivalent to the AJAX callback function.
Fourth Step, on the server side of the App.js, add the following code.

Io.sockets.on (' Connection ', function (socket) {
 socket.emit (' news ', {hello: ' world '});
 Socket.on (' Anothernews ', function (data) {
 console.log (data);});

The Io.sockets.on method of the above code specifies the callback function for the connection event (WebSocket connection establishment). In the callback function, the emit method is used to send data to the client, triggering the client's news event. Then, use the on method to specify the callback function for the server-side anothernews event.

Whether it is a server or a client, Socket.io provides two core methods: The Emit method is used to send messages, and the on method listens for messages sent by each other.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.