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

May 16, 2016 pm 03:48 PM
html5 websockets

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

See all articles