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 technology Polling(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).

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
}
}
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);
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"]);
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) {
//確定服務(wù)器選擇的協(xié)議
log(e.target.protocol);
}
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");
}
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();
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);
}
}
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);
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.實(shí)例
<!DOCTYPE html><html><head>
<title>webSocket實(shí)例</title></head><body>
<h2>webSocket實(shí)例</h2>
<input type="text" id="text">
<button type="" id="connect" onclick="connect()">建立連接</button>
<button type="" id="send" onclick="send()">發(fā)送數(shù)據(jù)</button>
<button type="" id="disconnect" onclick="disconnect()">斷開(kāi)連接</button>
<p id="message"></p>
<script type="text/javascript">
var socket; var readyState = ["正在連接","已經(jīng)連接","正在斷開(kāi)","已經(jīng)斷開(kāi)"]; var message = document.getElementById('message'); function connect(){
try{ var url = 'ws:localhost/test';
socket = new webSocket(url);
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
socket.onopen = function(){
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
}
socket.onmessage = function(msg){
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+'<br>'+ "接收數(shù)據(jù)" + msg.data +"</p>";
}
socket.onclose = function(){
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
}
}catch(exception){ // socket.onerror = function(){
message.innerHTML += "<p>發(fā)生錯(cuò)誤!"+"</p>"; // }
}
} function send(){
var text = document.getElementById('text').value; try{
socket.send(text);
message.innerHTML += "<p>發(fā)送數(shù)據(jù):" + text +"</p>";
}catch(exception){
message.innerHTML += "<p>發(fā)送數(shù)據(jù)出錯(cuò)</p>";
}
} function disconnect(){
socket.close();
} </script></body></html>
1.WebSocket通信基礎(chǔ)知識(shí)
WebSocket是HTML5開(kāi)始提供的一種瀏覽器與服務(wù)器間進(jìn)行全雙工通訊的網(wǎng)絡(luò)技術(shù)。 使用ws或wss協(xié)議,是下一代客戶端-服務(wù)器的異步通信方法。
在WebSocket API中,瀏覽器和服務(wù)器只需要要做一個(gè)握手的動(dòng)作,然后,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送。
現(xiàn)在,很多網(wǎng)站為了實(shí)現(xiàn)即時(shí)通訊(real-time),所用的技術(shù)都是輪詢(polling)。輪詢是在特定的的時(shí)間間隔(time interval)(如每1秒),由瀏覽器對(duì)服務(wù)器發(fā)出HTTP request,然后由服務(wù)器返回最新的數(shù)據(jù)給客服端的瀏覽器。這種傳統(tǒng)的HTTP request d的模式帶來(lái)很明顯的缺點(diǎn) – 瀏覽器需要不斷的向服務(wù)器發(fā)出請(qǐng)求(request),然而HTTP request 的header是非常長(zhǎng)的,里面包含的數(shù)據(jù)可能只是一個(gè)很小的值,這樣會(huì)占用很多的帶寬。
而最比較新的技術(shù)去做輪詢的效果是Comet – 用了AJAX。但這種技術(shù)雖然可達(dá)到全雙工通信,但依然需要發(fā)出請(qǐng)求(reuqest)。

在 WebSocket API,瀏覽器和服務(wù)器只需要要做一個(gè)握手的動(dòng)作,然后,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送。在此WebSocket 協(xié)議中,為我們實(shí)現(xiàn)即使服務(wù)帶來(lái)了兩大好處:
1. Header
互相溝通的Header是很小的-大概只有 2 Bytes
2. Server Push
服務(wù)器可以主動(dòng)傳送數(shù)據(jù)給客戶端,只要客戶端打開(kāi)的socket與服務(wù)器建立連接后,就可以把數(shù)據(jù)推送到這個(gè)socket上,從被動(dòng)轉(zhuǎn)為主動(dòng)。
WebSocket并不限于以Ajax(或XHR)方式通信,因?yàn)锳jax技術(shù)需要客戶端發(fā)起請(qǐng)求,而WebSocket服務(wù)器和客戶端可以彼此相互推送信息;XHR受到域的限制,而WebSocket允許跨域通信。
Ajax技術(shù)很聰明的一點(diǎn)是沒(méi)有設(shè)計(jì)要使用的方式。WebSocket為指定目標(biāo)創(chuàng)建,用于雙向推送消息。
2、HTML5 WebSockets API
WebSocket對(duì)象
WebSocket在DOM中是window對(duì)象的子對(duì)象,它具有:
WebSocket(url)構(gòu)造函數(shù)。
readyState。只讀屬性,其值可以是CONNECTING(0),OPEN(1),CLOSED(3)。
boolean send(in DOMString data)
void close()兩個(gè)方法,分別用于發(fā)送消息和關(guān)閉WebSocket連接
onopen, onmessage, 和onclosee三個(gè)事件屬性,分別對(duì)open, message和close三個(gè)WebSocket事件。
1、瀏覽器支持情況檢測(cè)
檢測(cè)瀏覽器支持情況
function loadDemo() {
if (window.WebSocket) {
//supported
} else {
// not supported
}
}
2、WebSocket對(duì)象的創(chuàng)建和服務(wù)器連接
要連接通信端點(diǎn),只需要?jiǎng)?chuàng)建一個(gè)新的WebSocket實(shí)例,并提供希望連接的對(duì)端URL。ws://和wss://前綴分別表示W(wǎng)ebSocket連接和安全的WebSocket連接。
url = "ws://localhost:8080/echo"; w = new WebSocket(url);
建立WebSocket連接時(shí),可以列出Web應(yīng)用能夠使用的協(xié)議。WebSocket構(gòu)造函數(shù)的第二個(gè)參數(shù)既可以是字符串,也可以是字符串組。
w = new WebSocket(url, ["proto1", "proto2"]);
假設(shè)proto1和proto2是定義明確、可能已注冊(cè)且標(biāo)準(zhǔn)化的協(xié)議名稱,它們能夠同時(shí)為客戶端和服務(wù)器端所理解。服務(wù)器會(huì)從列表中選擇首選協(xié)議。
onopen = function(e) {
//確定服務(wù)器選擇的協(xié)議
log(e.target.protocol);
}
3、添加事件監(jiān)聽(tīng)器
WebSocket編程遵循異步編程模型;打開(kāi)socket后,只需等待事件發(fā)生,而不需要主動(dòng)向服務(wù)器輪詢,所以需要在WebSocket對(duì)象中添加回調(diào)函數(shù)來(lái)監(jiān)聽(tīng)事件。
WebSocket對(duì)象有三個(gè)事件:open、close和message對(duì)應(yīng)有三個(gè)事件監(jiān)聽(tīng)器onopen,onmessage,onclose來(lái)處理連接的生命周期的每個(gè)階段,當(dāng)然還可以是onerror來(lái)監(jiān)聽(tīng)錯(cuò)誤,如以下示例所示。
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");
}
4、發(fā)送消息
當(dāng)socket處于打開(kāi)狀態(tài)(即onopen之后,onclose之前),可以用send方法來(lái)發(fā)送消息。消息發(fā)送完,可以調(diào)用close方法來(lái)終止連接,也可以不這么做,讓其保持打開(kāi)狀態(tài)。
w.send();
你可能想測(cè)算在調(diào)用Send()函數(shù)之前,有多少數(shù)據(jù)備份在發(fā)送緩沖區(qū)中。bufferAmount屬性表示已在WebSocket上發(fā)送但尚未寫入網(wǎng)絡(luò)的字節(jié)數(shù)。它對(duì)于調(diào)節(jié)發(fā)送速率很有用。
document.getElementById("sendButton").onclick = function() {
if (w.bufferedAmount < bufferThreshold) {
w.send(document.getElementById("inputMessage").value);
}
}
WebSocket API支持以二進(jìn)制數(shù)據(jù)的形式發(fā)送Blob和ArrayBuffer實(shí)例
var a = new Uint8Array([8, 6, 7, 5, 3, 0, 9]);
w.send(a.buffer);
常量-readyState屬性
這些常量是readyState屬性的取值,可以用來(lái)描述WebSocket連接的狀態(tài)。
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.實(shí)例
<!DOCTYPE html><html><head>
<title>webSocket實(shí)例</title></head><body>
<h2>webSocket實(shí)例</h2>
<input type="text" id="text">
<button type="" id="connect" onclick="connect()">建立連接</button>
<button type="" id="send" onclick="send()">發(fā)送數(shù)據(jù)</button>
<button type="" id="disconnect" onclick="disconnect()">斷開(kāi)連接</button>
<p id="message"></p>
<script type="text/javascript">
var socket; var readyState = ["正在連接","已經(jīng)連接","正在斷開(kāi)","已經(jīng)斷開(kāi)"]; var message = document.getElementById('message'); function connect(){
try{ var url = 'ws:localhost/test';
socket = new webSocket(url);
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
socket.onopen = function(){
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
}
socket.onmessage = function(msg){
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+'<br>'+ "接收數(shù)據(jù)" + msg.data +"</p>";
}
socket.onclose = function(){
message.innerHTML += "<p>socket狀態(tài):" +readyState[socket.readyState]+"</p>";
}
}catch(exception){ // socket.onerror = function(){
message.innerHTML += "<p>發(fā)生錯(cuò)誤!"+"</p>"; // }
}
} function send(){
var text = document.getElementById('text').value; try{
socket.send(text);
message.innerHTML += "<p>發(fā)送數(shù)據(jù):" + text +"</p>";
}catch(exception){
message.innerHTML += "<p>發(fā)送數(shù)據(jù)出錯(cuò)</p>";
}
} function disconnect(){
socket.close();
} </script></body></html>
?以上就是Html5 中的 WebSocket通信的內(nèi)容,更多相關(guān)內(nèi)容請(qǐng)關(guān)注PHP中文網(wǎng)(m.miracleart.cn)!