Home  >  Article  >  Web Front-end  >  HTML5 new features WebSocket

HTML5 new features WebSocket

黄舟
黄舟Original
2017-03-30 11:40:031509browse

1. Overview

HTTP protocol is a stateless protocol. The server itself does not have the ability to identify the client and must rely on external mechanisms, such assession and cookie to maintain a conversation 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). In order to solve this problem, HTML5 proposed 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 have to 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 the HTTP protocol, but its own protocol. The WebSocket request issued by the browser is similar to the following:

GET / HTTP/1.1Connection: Upgrade
Upgrade: websocket
Host: example.com
Origin: nullSec-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 switching the communication protocol from HTTP1.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 server's permission range. Sec-WebSocket-Key is the key used for the handshake protocol, which is a base64-encoded 16-byte random string.

The server's WebSocket response is:

HTTP/1.1 101 Switching ProtocolsConnection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=Sec-WebSocket-Origin: 
nullSec-WebSocket-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## of sha-1. #value. The browser will verify this value to prove that it is indeed the target server that responded to the webSocket request. Sec-WebSocket-Location indicates the WebSocket URL of the communication.

Note: 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 IE10+), the only exceptions are Opera Mini and Android Browser on the mobile phone.

2. Client

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

  • Establishing a connection and disconnecting

  • Sending data and receiving data

  • Handling errors

2.1 Establishing and disconnecting connections

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) {    // 支持}

Then, start to establish a connection with the server (it is assumed that the server is the 1740 port of this machine and the ws protocol needs to be used).

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

The WebSocket instance after establishing the connectionObject (that is, the connection in the above code) has a readyState attribute, indicating the current status, which can take 4 values:

  • 0: Connecting

  • 1: Connection successful

  • 2: Closing

  • 3: The connection is closed

After the handshake protocol is successful, readyState changes from 0 to 1, and the open

event is triggered. At this time, you can send information to the server. We can specify the callback function of the open event.

connection.onopen = wsOpen;function wsOpen(event) {
    console.log('Connected');
}

Close WebSocket will trigger the close event.

connection.onclose = wsClose;function onClose(event) {    var wasClean = event.wasClean; //bool值,连接是否关闭了
    var code = event.code; //连接状态(数字),由服务端提供
    var reason = event.reason; //关闭原因,由服务端提供
    console.log('Closed');
}

connection.close();

2.2 Sending 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 Unit8Array(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(&#39;input[type="file"]&#39;).files[0];
connection.send(file);

客户端收到服务器发送的数据,会触发message事件。可以通过定义message事件的回调函数,来处理服务端返回的数据。

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

上面代码的回调函数wsMessage的参数为事件对象evnet,该对象的data属性包含了服务器返回的数据。

2.3 处理错误

如果出现错误,浏览器会触发WebSocket实例对象的error事件。

connection.onerror = wsError;function wsError(event) {
    console.log(&#39;Error: &#39; + event.data);
}

3、服务器端

服务器端需要单独部署处理WebSocket的代码。下面用node.js搭建一个服务器环境。

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

假设监听1740端口。

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

接着启动WebSocket服务器。这需要加载websocket库,如果没有安装,可以先使用命令安装。

var WebSocketServer = require(&#39;websocket&#39;).server;var wsServer = new WebSocketServer({
    httpServer: server
});

WebSocket服务器建立request事件的回调函数。

var connection;

wsServer.on(&#39;request&#39;, function(req){
    connect = req.accept(&#39;echo-protocol&#39;, req.origin);
});

上面代码的回调函数接受一个参数req,表示request请求对象。然后,在回调函数内部,建立WebSocket连接Connection。接着,就要对connection的message事件指定回调函数。

wsServer.on(&#39;request&#39;, function(r) {
    connection = req.accept(&#39;echo-protocol&#39;, req.origin);

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

最后,监听用户的disconnect事件。

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

4、Socket.io简介

Socket.io是目前最流行的WebSocket实现,包括服务器和浏览器两个部分。它不仅简化了接口,使得操作更容易,而且对于那些不支持WebSocket的浏览器,会自动降为Ajax连接,最大限度地保证了兼容性。

第一步,在服务器端的项目根目录下,安装socket.io模块。

npm install socket.io

第二步,在根目录下建立app.js,并写入以下代码(使定使用了Express框架)。

var app = require(&#39;express&#39;)();
var server = require(&#39;http&#39;).createServer(app);
var io = require(&#39;socket.io&#39;).listen(server);

server.listen(80);

app.get(&#39;/&#39;, function (req, res) {
  res.sendfile(dirname + &#39;/index.html&#39;);
});

上面代码表示,先建立并运行HTTP服务器。Socket.io的运行建立在HTTP服务器之上。

第三步,将Socket.io插入客户端网页。

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

然后,在客户端脚本中,建立WebSocket连接。

var socket = io.connect(&#39;http://localhost&#39;);

由于本例假定WebSocket主机与客户端是同一台机器,所以connect方法的参数是http://localhost。接着,指定news事件(即服务器端发送news)的回调函数。

socket.on(&#39;news&#39;, function (data){
   console.log(data);
});

最后,用emit方法向服务器端发送信号,触发服务器端的anotherNews事件。

请注意:emit方法可以取代Ajax请求,而on方法指定的回调函数,也等同于Ajax的回调函数。

第四步,在服务器端的app.js中加入以下代码。

io.sockets.on(&#39;connection&#39;, function (socket) {
  socket.emit(&#39;news&#39;, { hello: &#39;world&#39; });
  socket.on(&#39;anotherNews&#39;, function (data) {
    console.log(data);
  });
});

上面代码的io.sockets.on方法指定connect事件(WebSocket连接建立)的回调函数。在回调函数中,用emit方法向客户端发送数据,触发客户端的news事件。然后,再用on方法指定服务器端anotherNews事件的回调函数。

The above is the detailed content of HTML5 new features WebSocket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn