Home >Web Front-end >H5 Tutorial >HTML5 websockets full-duplex communication detailed learning example_html5 tutorial skills

HTML5 websockets full-duplex communication detailed learning example_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:48:191859browse

Most of the current implementations of real-time web applications revolve around polling and other server-side push technologies, the most famous of which is Comet. Comet technology allows the server to actively push data to the client in an asynchronous manner.

When using polling, the browser sends HTTP requests periodically and receives responses immediately; when using long polling, the browser sends a request to the server, and the server keeps it open for a period of time; use streams to solve scenario, the browser sends a full HTTP request, but the server sends and keeps an open response that continues to update and remains open indefinitely.

The above three methods will involve HTTP request and response headers when sending real-time data, and contain a large amount of additional and unnecessary header data, which will cause transmission delays.

1. Interpretation of HTML5 WebSockets

1. WebSocket handshake

In order to establish WebSocket communication, the client and server upgrade the HTTP protocol to the WebSocket protocol during the initial handshake. Once the connection is established, WebSocket messages can be sent back and forth between the client and server in full-duplex mode.

Note: In the network, each message starts with 0x00 bytes and ends with 0xFF, and the intermediate data uses UTF-8 encoding format.

2. WebSocket interface

In addition to the definition of the WebSocket protocol, the WebSocket interface for JavaScript applications is also defined.

Copy code
The code is as follows:

interface WebSocket{
readonly attribute DOMString URL;
//Ready state
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSED = 2;
readonly attribute unsigned short readyState;
readonly attribute unsigned short bufferedAmount;
//Network
attribute Function onopen;
attribute Function onmessage;
attribute Function onclose;
boolean send(in DOMSString data);
void close ();
};
WebSocket implements EventTarget;


Note: The ws:// and wss:// prefixes represent WebSocket connections and secure WebSocket connections respectively.

2. HTML5 WebSockets API

This section discusses how to use HTML5 WebSockets

1. Check whether the browser supports it

Use window.WebSocket to determine whether the browser supports it.

2. Basic usage of API

a. Creation of WebSocket objects and connection to WebSocket server


Copy code
The code is as follows:

url = "ws://localhost: 8080/echo";
ws = new WebSocket(url);

b. Add event listener

WebSocket follows the asynchronous programming model. After opening the socket, you only need to wait for events to occur without actively polling the server. Therefore, you need to add a callback function to listen for events.

WebSocket object has three events: open, close and message. The open event is triggered when the connection is established, the message event is triggered when a message is received, and the close event is triggered when the WebSocket connection is closed.


Copy code
The code is as follows:

ws.onopen = function(){
log("open");
}
ws.onmessage = function(){
log(e.data);
}
ws.onclose = function(){
log("closed");
}

c. Send message

When the socket is open (that is, after calling the onopen listener and before calling the onclose listener), you can use the send method to send a message.

ws.send("Hello World");

3. HTML5 WebSockets application examples

This section will combine the previously described Geolocation interface to create an application that calculates distance directly in the Web page.

1. Write HTML file


Copy code
The code is as follows:

HTML5 WebSocket / Geolocation Tracker

HTML5 WebSocket / Geolocation Tracker

Geolocation:

Your browser does not support HTML5 Geolocation

WebSocket:

Your browser does not support HTML5 Web Sockets


2. Add WebSocket code


Copy code
The code is as follows:

function loadDemo(){
/ /Make sure the browser supports WebSocket
if(window.WebSocket){
url = "ws://localhost:8080";//broadcast WebSocket server location
ws = new WebSocket(url);
ws.onopen = function(){
updateSocketStatus("Connection established");
}
ws.onmessage = function(e){
updateSocketeStatus("Update location data:" dataReturned( e.data));
}
}
}

3. Add Geolocation code


Copy code
The code is as follows:

var geo;
if(navigator .geolocation){
geo = navigator.geolocation;
updateGeolocationStatus("The browser supports HTML5 Geolocation");
}

geo.watchPosition(updateLocation,handleLocationError,{maximumAge:20000});//Update every 20s

function updateLocation(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var timestamp = position.timestamp;
updateGeolocationStatus(" Location update time: " timestamp);
var toSend = JSON.stringify([myId,latitude,longitude]);
sendMyLocation(toSend);
}

4. Merge all content


Copy code
The code is as follows:

HTML5 WebSocket / Geolocation 追踪器

HTML5 WebSocket / Geolocation 追踪器

Geolocation:

你的浏览器不支持HTML5 Geolocation

WebSocket:

你的浏览器不支持HTML5 Web Sockets

<script></p> <p> //Reference to WebSocket</p> <p> var ws;</p> <p> //The unique random ID generated for this session</p> <p> var myId = Math.floor(100000*Math.random());</p> <p> //Number of rows currently displayed</p> <p> var rowCount;</p> <p> function updateSocketStatus(message){</p> <p> document.getElementById("socketStatus").innerHTML = message;</p> <p> }</p> <p> function updateGeolocationStatus(message){</p> <p> document.getElementById("geoStatus").innerHTML = message;</p> <p> }</p> <p> function loadDemo(){</p> <p> //Make sure the browser supports WebSocket</p> <p> if(window.WebSocket){</p> <p> url = "ws://localhost:8080";//broadcast WebSocket server location</p> <p> ws = new WebSocket(url);</p> <p> ws.onopen = function(){</p> <p> updateSocketStatus("Connection established");</p> <p> }</p> <p> ws.onmessage = function(e){</p> <p> updateSocketStatus("Update location data:" dataReturned(e.data));</p> <p> }</p> <p> }</p> <p> var geo;</p> <p> if(navigator.geolocation){</p> <p> geo = navigator.geolocation;</p> <p> updateGeolocationStatus("The browser supports HTML5 Geolocation");</p> <p> }</p> <p> geo.watchPosition(updateLocation,handleLocationError,{maximumAge:20000});//Update every 20s</p> <p> function updateLocation(position){</p> <p> var latitude = position.coords.latitude;</p> <p> var longitude = position.coords.longitude;</p> <p> var timestamp = position.timestamp;</p> <p> updateGeolocationStatus("Location update time: " timestamp);</p> <p> var toSend = JSON.stringify([myId,latitude,longitude]);</p> <p> sendMyLocation(toSend);</p> <p> }</p> <p> function sendMyLocation(newLocation){</p> <p> if(ws){</p> <p> ws.send(newLocation)</p> <p> }</p> <p> }</p> <p> function dataReturned(locationData){</p> <p> var allData = JSON.parse(locationData);</p> <p> var incomingId = allData[1];</p> <p> var incomingLat = allData[2];</p> <p> var incomingLong = allData[3];</p> <p> var incomingRow = document.getElementById(incomingId);</p> <p> if(!incomingRow){</p> <p> incomingRow = document.getElementById("div");</p> <p> incomingRow.setAttribute("id",incomingId);</p> <p> incomingRow.userText = (incomingId == myId)?"Me":'User' rowCount;</p> <p> rowCount ;</p> <p> document.body.appendChild(incomingRow);</p> <p> }</p> <p> incomingRow.innerHTML = incomingRow.userText " \ Lat: " </p> <p> incomingLat " \ Lon: " </p> <p> incomingLong;</p> <p> return incomingRow.userText;</p> <p> }</p> <p> function handleLocationError(error){</p> <p> switch(error.code){</p> <p> case 0:</p> <p>updateGeolocationStatus("Error retrieving location information: " error.message);</p> <p>break;</p> <p> case 1:</p> <p>updateGeolocationStatus("The user blocks access to location information.");</p> <p>break;</p> <p> case 2:</p> <p>updateGeolocationStatus("The browser cannot detect your location information: " error.message);</p> <p>break;</p> <p> case 3:</p> <p>updateGeolocationStatus("The browser timed out when retrieving location information.");</p> <p>break;</p> <p> }<br> }</p> <p> </script>


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