WebSocket communication in Html5

黄舟
Release: 2017-02-16 14:29:40
Original
3162 people have browsed it

1. Basic knowledge of WebSocket communication

WebSocket is a network technology for full-duplex communication between browsers and servers that HTML5 began to provide. Using ws or wss protocol, it is the next generation client-server asynchronous communication method.

In the WebSocket API, the browser and the server only need to perform a handshake action, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

Now, in order to achieve instant messaging (real-time), many websites use the technologyPolling(polling). Polling is when the browser sends an HTTP request to the server at a specific time interval (such as every 1 second), and then the server returns the latest data to the client's browser. This traditional HTTP request d model brings obvious shortcomings – the browser needs to continuously send requests to the server. However, the header of the HTTP request is very long, and the data contained in it may only be a small value. , which will take up a lot of bandwidth.

The latest technology to achieve the effect of polling is Comet - using AJAX. However, although this technology can achieve full-duplex communication, it still needs to issue a request (reuqest).

WebSocket communication in Html5

In the WebSocket API, the browser and the server only need to do a handshake action, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two. In this WebSocket protocol, it brings us two major benefits to achieve instant service:

1. Header

#The Header that communicates with each other is very small - about only 2 Bytes

2. Server Push

The server can actively transmit data to the client. As long as the socket opened by the client establishes a connection with the server, the data can be pushed. Go to this socket and change from passive to active.

WebSocket is not limited to Ajax (or XHR) communication, because Ajax technology requires the client to initiate a request, and the WebSocket server and client can push information to each other; domain communication.
The smart thing about Ajax technology is that there is no designed way to use it. WebSocket is created for the specified target and used to push messages in both directions.

2. HTML5 WebSockets API

WebSocket object

WebSocket is a sub-object of the window object in the DOM. It has:

  • WebSocket(url) constructor.

  • readyState. Read-only attribute, its value can be CONNECTING (0), OPEN (1), CLOSED (3).

  • boolean send(in DOMString data)

  • void close() two methods, used to send messages and close WebSocket connections respectively

onopen, onmessage, and onclosee event attributes, respectively for the three WebSocket events of open, message, and close.

1. Browser support detection

Detection of browser support

function loadDemo() { if (window.WebSocket) { //supported } else { // not supported } }
Copy after login
Copy after login

2. Creation of WebSocket objects and server connection

Requirements To connect to a communication endpoint, simply create a new WebSocket instance and provide the URL of the peer you wish to connect to. The ws:// and wss:// prefixes represent WebSocket connections and secure WebSocket connections respectively.

url = "ws://localhost:8080/echo"; w = new WebSocket(url);
Copy after login
Copy after login

When establishing a WebSocket connection, you can list the protocols that the web application can use. The second parameter of the WebSocket constructor can be either a string or a group of strings.

w = new WebSocket(url, ["proto1", "proto2"]);
Copy after login
Copy after login

Assume that proto1 and proto2 are well-defined, possibly registered, and standardized protocol names that can be understood by both the client and the server. The server selects the preferred protocol from the list.

onopen = function(e) { //确定服务器选择的协议 log(e.target.protocol); }
Copy after login
Copy after login

3. Add event listener

WebSocket programming follows the asynchronous programming model; after opening the socket, you only need to wait for the event to occur without actively polling the server, so you need to add the event listener to the WebSocket object. Add a callback function to listen for events.
The WebSocket object has three events:open, close and messageThere are three corresponding event listeners onopen, onmessage and onclose to handle each stage of the connection life cycle. Of course, onerror can also be used to listen for errors. , as shown in the following example.

w.onopen = function() { log("open"); w.send("send message"); } w.onmessage = function(e) { log(e.data); } w.onclose = function(e) { log("closed"); } w.onerror = function(e) { log("error"); }
Copy after login
Copy after login

4. Send a message

When the socket is open (that is, after onopen and before onclose), you can use the send method to send a message. After the message is sent, you can call the close method to terminate the connection, or you can not do this and keep it open.

w.send();
Copy after login
Copy after login

You may want to measure how much data is backed up in the send buffer before calling the Send() function. The bufferAmount property represents the number of bytes that have been sent on the WebSocket but not yet written to the network. It is useful for adjusting the sending rate.

document.getElementById("sendButton").onclick = function() { if (w.bufferedAmount < bufferThreshold) { w.send(document.getElementById("inputMessage").value); } }
Copy after login
Copy after login

WebSocket API supports sending Blob and ArrayBuffer instances in the form of binary data

var a = new Uint8Array([8, 6, 7, 5, 3, 0, 9]); w.send(a.buffer);
Copy after login
Copy after login

Constant-readyState attribute

These constants are the takers of the readyState attribute Value, which can be used to describe the status of the WebSocket connection.

Constant Value Description
CONNECTING 0 The connection has not been opened yet.
OPEN 1 The connection is open and ready for communication.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection has been closed, or the connection cannot be established.

3.实例

 webSocket实例
 

webSocket实例

Copy after login
Copy after login

1.WebSocket通信基础知识

WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。 使用ws或wss协议,是下一代客户端-服务器的异步通信方法。

在WebSocket API中,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

现在,很多网站为了实现即时通讯(real-time),所用的技术都是轮询(polling)。轮询是在特定的的时间间隔(time interval)(如每1秒),由浏览器对服务器发出HTTP request,然后由服务器返回最新的数据给客服端的浏览器。这种传统的HTTP request d的模式带来很明显的缺点 – 浏览器需要不断的向服务器发出请求(request),然而HTTP request 的header是非常长的,里面包含的数据可能只是一个很小的值,这样会占用很多的带宽。

而最比较新的技术去做轮询的效果是Comet – 用了AJAX。但这种技术虽然可达到全双工通信,但依然需要发出请求(reuqest)。

WebSocket communication in Html5

在 WebSocket API,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。在此WebSocket 协议中,为我们实现即使服务带来了两大好处:

1. Header

互相沟通的Header是很小的-大概只有 2 Bytes

2. Server Push

服务器可以主动传送数据给客户端,只要客户端打开的socket与服务器建立连接后,就可以把数据推送到这个socket上,从被动转为主动。

WebSocket并不限于以Ajax(或XHR)方式通信,因为Ajax技术需要客户端发起请求,而WebSocket服务器和客户端可以彼此相互推送信息;XHR受到域的限制,而WebSocket允许跨域通信。
Ajax技术很聪明的一点是没有设计要使用的方式。WebSocket为指定目标创建,用于双向推送消息。

2、HTML5 WebSockets API

WebSocket对象

WebSocket在DOM中是window对象的子对象,它具有:

  • WebSocket(url)构造函数。

  • readyState。只读属性,其值可以是CONNECTING(0),OPEN(1),CLOSED(3)。

  • boolean send(in DOMString data)

  • void close()两个方法,分别用于发送消息和关闭WebSocket连接

onopen, onmessage, 和onclosee三个事件属性,分别对open, message和close三个WebSocket事件。

1、浏览器支持情况检测

检测浏览器支持情况

function loadDemo() { if (window.WebSocket) { //supported } else { // not supported } }
Copy after login
Copy after login

2、WebSocket对象的创建和服务器连接

要连接通信端点,只需要创建一个新的WebSocket实例,并提供希望连接的对端URL。ws://和wss://前缀分别表示WebSocket连接和安全的WebSocket连接。

url = "ws://localhost:8080/echo"; w = new WebSocket(url);
Copy after login
Copy after login

建立WebSocket连接时,可以列出Web应用能够使用的协议。WebSocket构造函数的第二个参数既可以是字符串,也可以是字符串组。

w = new WebSocket(url, ["proto1", "proto2"]);
Copy after login
Copy after login

假设proto1和proto2是定义明确、可能已注册且标准化的协议名称,它们能够同时为客户端和服务器端所理解。服务器会从列表中选择首选协议。

onopen = function(e) { //确定服务器选择的协议 log(e.target.protocol); }
Copy after login
Copy after login

3、添加事件监听器

WebSocket编程遵循异步编程模型;打开socket后,只需等待事件发生,而不需要主动向服务器轮询,所以需要在WebSocket对象中添加回调函数来监听事件。
WebSocket对象有三个事件:open、close和message对应有三个事件监听器onopen,onmessage,onclose来处理连接的生命周期的每个阶段,当然还可以是onerror来监听错误,如以下示例所示。

w.onopen = function() { log("open"); w.send("send message"); } w.onmessage = function(e) { log(e.data); } w.onclose = function(e) { log("closed"); } w.onerror = function(e) { log("error"); }
Copy after login
Copy after login

4、发送消息

当socket处于打开状态(即onopen之后,onclose之前),可以用send方法来发送消息。消息发送完,可以调用close方法来终止连接,也可以不这么做,让其保持打开状态。

w.send();
Copy after login
Copy after login

你可能想测算在调用Send()函数之前,有多少数据备份在发送缓冲区中。bufferAmount属性表示已在WebSocket上发送但尚未写入网络的字节数。它对于调节发送速率很有用。

document.getElementById("sendButton").onclick = function() { if (w.bufferedAmount < bufferThreshold) { w.send(document.getElementById("inputMessage").value); } }
Copy after login
Copy after login

WebSocket API支持以二进制数据的形式发送Blob和ArrayBuffer实例

var a = new Uint8Array([8, 6, 7, 5, 3, 0, 9]); w.send(a.buffer);
Copy after login
Copy after login

常量-readyState属性

这些常量是readyState属性的取值,可以用来描述WebSocket连接的状态。

Constant Value Description
CONNECTING 0 The connection has not been opened yet.
OPEN 1 The connection is open and ready for communication.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection has been closed, or the connection cannot be established.

3.实例

 webSocket实例
 

webSocket实例

Copy after login
Copy after login

以上就是Html5 中的 WebSocket通信的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!