WebSocket Technology in JavaScript

Source: Internet
Author: User
Tags key string
Overview of WebSocket Technology in JavaScript

HTTP is a stateless protocol. The server itself does not have the ability to identify the client. It must use external mechanisms, such as session and cookie, to maintain a conversation with a specific client. This is more or less inconvenient, especially when the server and client need to continuously exchange data (such as online chat. To solve this problem, HTML5 proposes the WebSocket API of the browser.

The main function of WebSocket is to allow full-duplex communication between the server and the client. For example, the HTTP protocol is a bit like sending an email. after sending an email, you must wait for the reply from the other party. WebSocket is like making a call. The server and client can send data to the other party at the same time, there is a continuously open data channel between them.

The WebSocket protocol can completely replace the Ajax method to send text and binary data to the server, and there is no "same domain limit" yet ".

WebSocket uses its own protocol instead of HTTP. The WebSocket request sent by the browser is similar to 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 above header information shows that an HTTP header is Upgrade. According to HTTP1.1, the Upgrade header indicates that the communication protocol is switched from HTTP/1.1 to the specified protocol. "Connection: Upgrade" indicates that the browser notifies the server. If yes, Upgrade to the webSocket protocol. Origin is used to verify whether the browser domain name is within the permitted range of the server. The Sec-WebSocket-Key is the Key used for the handshake protocol and is a base64-encoded 16-byte random string.

The WebSocket response on the server is

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s =
Sec-WebSocket-Origin: null
Sec-WebSocket-Location: ws: // example.com/

The server also uses "Connection: Upgrade" to notify the browser that the Protocol needs to be changed. The Sec-WebSocket-Accept is the server following the Sec-WebSocket-Key string provided by the browser. Add the "258eafa5-e914-4710995ca-c5ab0dc85b11" string and then take the hash value of sha-1. The browser will verify this value to prove that the target server has responded to the webSocket request. Sec-WebSocket-Location indicates the WebSocket URL for communication.

Note that the WebSocket protocol is represented by ws. In addition, there is also the wss protocol, indicating the encrypted WebSocket protocol, corresponding to the HTTPs protocol.
After the handshake is completed, the WebSocket protocol starts to transmit data over the TCP protocol.

The WebSocket protocol requires server support. Currently, the popular implementations are socket. io Based on node. js. For more implementations, see Wikipedia. Currently, mainstream browsers support the WebSocket Protocol (including IE 10 +). The only exceptions are Opera Mini and Android Browser on mobile phones.

Client

The processing of WebSocket protocol on the browser is nothing more than three things:

Establish and disconnect
Send and receive data
Handling error

Establish and disconnect

First, the client should check whether the browser supports WebSocket by checking whether the window object has the WebSocket attribute.

If (window. WebSocket! = Undefined) {// WebSocket code}


Then, start to establish a connection with the server (assuming that the server is the port 1740 of the local machine, the ws Protocol is required ).

if(window.WebSocket != undefined) {  var connection = new WebSocket('ws://localhost:1740'); }


The WebSocket instance object after the connection is established (the connection in the code above) has a readyState attribute, indicating the current status. You can set four values:

0: Connecting
1: Connection successful
2: Closing
3: the connection is closed.
After the handshake is successful, the readyState changes from 0 to 1, and the open event is triggered. Then, you can send information to the server. You can specify the callback function for an 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();


Send and receive data

After the connection is established, the client sends data to the server through the send method.

Connection. send (message );
In addition to sending strings, you can also use Blob or ArrayBuffer objects to send binary data.

// Use ArrayBuffer to send canvas image data var img = canvas_context.getImageData (0, 0,400,320); var binary = new Uint8Array (img. data. length); for (var I = 0; I 


When the client receives data from the server, a message event is triggered. You can define the callback function of the message event to process the data returned by the server.

Connection. onmessage = wsMessage;

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


The parameter of the callback function wsMessage in the code above is the event object. The data attribute of this object contains the data returned by the server.

If binary data is received, set the format of the connection object to blob or arraybuffer.

Connection. binaryType = 'arraybuffer'; connection. onmessage = function (e) {console. log (e. data. byteLength); // The arraybuffer object has the byteLength attribute };


Handling error

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

Connection. onerror = wsError;

function wsError(event) {console.log(“Error: “ + event.data);}


Server

The server must separately deploy the code for processing WebSocket. Next we will use node. js to build a server environment.

var http = require('http'); var server = http.createServer(function(request, response) {});


Assume that the listener is listening to port 1740.

server.listen(1740, function() {  console.log((new Date()) + ' Server is listening on port 1740'); });


Start the WebSocket server. This requires loading the websocket library. If the library is not installed, run the npm command first.

Var WebSocketServer = require ('websocket '). server; var wsServer = new WebSocketServer ({httpServer: server}); websocket server creates a callback function for the request event. Var connection; wsServer. on ('request', function (req ){
connection = req.accept(‘echo-protocol', req.origin);});


The callback function in the code above accepts a req parameter, indicating the request object. Then, establish a WebSocket connection within the callback function. Next, we need to specify a callback function for the message event of the connection.

wsServer.on(‘request', function(r){  connection = req.accept(‘echo-protocol', req.origin);

connection.on('message', function(message) { var msgString = message.utf8Data; connection.sendUTF(msgString);});});


Finally, listen to the user's disconnect event.

connection.on('close', function(reasonCode, description) {  console.log(connection.remoteAddress + ' disconnected.'); });


Using the ws module, it is very 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 the server and client. It not only simplifies the interface and makes operations easier, but also automatically reduces the number of browsers that do not support WebSocket to Ajax connections to maximize compatibility. It aims to achieve a unified communication mechanism so that all browsers and mobile devices can communicate in real time.

Step 1: Install the socket. io module under the root directory of the project on the server side.

$ Npm install socket. io

Step 2: Create 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(80); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html');});


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

Step 3: insert Socket. io into the client webpage.

Related Article

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.