Home > Article > Web Front-end > Detailed explanation of WebSocket technology in JavaScript
Overview
HTTP protocol is a stateless protocol. The server itself does not have the ability to identify the client. It must rely on external mechanisms, such as sessions and cookies, to maintain a dialogue with a specific client. This brings some inconvenience, especially in situations where the server and client need to continuously exchange data (such as online chat). To solve this problem, HTML5 proposes the browser's WebSocket API.
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, and you must wait for the other party to reply after sending it; WebSocket is like making a phone call, the server and the client can send data to each other at the same time, and there is a continuously open data channel between them.
The WebSocket protocol can completely replace the Ajax method and be used to send text and binary data to the server, and there is no "same domain restriction".
WebSocket does not use HTTP protocol, but its own protocol. The WebSocket request made by the browser looks 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 header information above shows that there is an HTTP header for Upgrade. The HTTP1.1 protocol stipulates that the Upgrade header information indicates changing the communication protocol from HTTP/1.1 to the protocol specified by the item. "Connection: Upgrade" means that the browser notifies the server to upgrade to the webSocket protocol if possible. Origin is used to verify whether the browser domain name is within the scope permitted by the server. Sec-WebSocket-Key is the key used for the handshake protocol, which is a base64-encoded 16-byte random string.
The server-side WebSocket response is
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=
Sec-WebSocket-Origin: null
Sec-WebSock et-Location: ws: //example.com/
The server also uses "Connection: Upgrade" to notify the browser that the protocol needs to be changed. Sec-WebSocket-Accept means that the server adds the "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" string after the Sec-WebSocket-Key string provided by the browser, and then takes the hash value of sha-1. The browser will verify this value to prove that it is indeed the target server that responded to the webSocket request. Sec-WebSocket-Location represents the WebSocket URL for communication.
Please note that the WebSocket protocol is represented by ws. In addition, there is the wss protocol, which represents the encrypted WebSocket protocol and corresponds to the HTTPs protocol.
After completing the handshake, the WebSocket protocol is on top of the TCP protocol and starts transmitting data.
WebSocket protocol requires server support. Currently, the more popular implementation is socket.io based on node.js. For more implementations, please refer to Wikipedia. As for the browser side, currently all mainstream browsers support the WebSocket protocol (including IE 10+), with the only exceptions being Opera Mini and Android Browser on the mobile phone.
The client side
The browser side's processing of the WebSocket protocol is nothing more than three things:
Establishing a connection and disconnecting
Sending data and receiving data
Handling errors
Establishing a connection and disconnecting
First , the client needs to check whether the browser supports WebSocket by checking whether the window object has the WebSocket attribute.
if(window.WebSocket != undefined) { // WebSocket代码 }
Then, start to establish a connection with the server (it is assumed that the server is the 1740 port of the local machine and the ws protocol needs to be used).
if(window.WebSocket != undefined) { var connection = new WebSocket('ws://localhost:1740'); }
After establishing a connection, the WebSocket instance object (that is, the connection in the above code) has a readyState attribute, which represents the current status and can take 4 values:
0: Connecting
1: Connected Success
2: Closing
3: Connection closed
After the handshake protocol is successful, readyState changes from 0 to 1 and the open event is triggered. At this time, information 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 will trigger 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 through the send method.
connection.send(message);
In addition to sending strings, you can also use Blob or ArrayBuffer objects to send binary data.
// 使用ArrayBuffer发送canvas图像数据 var img = canvas_context.getImageData(0, 0, 400, 320); 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); // 使用Blob发送文件 var file = document.querySelector(‘input[type=”file”]').files[0]; connection.send(file);
When the client receives the data sent by the server, the message event will be triggered. You can process the data returned by the server by defining a callback function for the message event.
connection.onmessage = wsMessage;
function wsMessage (event) { console.log(event.data); }
The parameter of the callback function wsMessage in the above code is the event object event, and the data attribute of the object contains the data returned by the server.
If you receive binary data, you need to set the format of the connection object to blob or arraybuffer.
connection.binaryType = 'arraybuffer'; connection.onmessage = function(e) { console.log(e.data.byteLength); // ArrayBuffer对象有byteLength属性 };
Handling errors
If an error occurs, the browser will trigger the error event of the WebSocket instance object.
connection.onerror = wsError;
function wsError(event) { console.log(“Error: “ + event.data); }
服务器端
服务器端需要单独部署处理WebSocket的代码。下面用node.js搭建一个服务器环境。
var http = require('http'); var server = http.createServer(function(request, response) {});
假设监听1740端口。
server.listen(1740, function() { console.log((new Date()) + ' Server is listening on port 1740'); });
接着启动WebSocket服务器。这需要加载websocket库,如果没有安装,可以先使用npm命令安装。
var WebSocketServer = require('websocket').server; var wsServer = new WebSocketServer({ httpServer: server }); WebSocket服务器建立request事件的回调函数。 var connection;wsServer.on(‘request', function(req){
connection = req.accept(‘echo-protocol', req.origin); });
上面代码的回调函数接受一个参数req,表示request请求对象。然后,在回调函数内部,建立WebSocket连接connection。接着,就要对connection的message事件指定回调函数。
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> });
最后,监听用户的disconnect事件。
connection.on('close', function(reasonCode, description) { console.log(connection.remoteAddress + ' disconnected.'); });
使用ws模块,部署一个简单的WebSocket服务器非常容易。
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简介
Socket.io是目前最流行的WebSocket实现,包括服务器和客户端两个部分。它不仅简化了接口,使得操作更容易,而且对于那些不支持WebSocket的浏览器,会自动降为Ajax连接,最大限度地保证了兼容性。它的目标是统一通信机制,使得所有浏览器和移动设备都可以进行实时通信。
第一步,在服务器端的项目根目录下,安装socket.io模块。
$ npm install socket.io
第二步,在根目录下建立app.js,并写入以下代码(假定使用了Express框架)。
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'); });
上面代码表示,先建立并运行HTTP服务器。Socket.io的运行建立在HTTP服务器之上。
第三步,将Socket.io插入客户端网页。
b87e043dd6e28f8c8a3dcd50a2ffa1652cacc6d41bbb37262a98f745aa00fbf0
然后,在客户端脚本中,建立WebSocket连接。
var socket = io.connect('http://localhost:80');
由于本例假定WebSocket主机与客户端是同一台机器,所以connect方法的参数是http://localhost。接着,指定news事件(即服务器端发送news)的回调函数。
socket.on('news', function (data){ console.log(data); });
最后,用emit方法向服务器端发送信号,触发服务器端的anotherNews事件。
socket.emit('anotherNews');
请注意,emit方法可以取代Ajax请求,而on方法指定的回调函数,也等同于Ajax的回调函数。
第四步,在服务器端的app.js,加入以下代码。
io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('anotherNews', function (data) { console.log(data); }); }) ;
上面代码的io.sockets.on方法指定connection事件(WebSocket连接建立)的回调函数。在回调函数中,用emit方法向客户端发送数据,触发客户端的news事件。然后,再用on方法指定服务器端anotherNews事件的回调函数。
不管是服务器还是客户端,socket.io提供两个核心方法:emit方法用于发送消息,on方法用于监听对方发送的消息。