search
HomeWeb Front-endH5 TutorialHTML5 websockets full-duplex communication detailed learning example_html5 tutorial skills

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

//Reference to WebSocket

var ws;

//The unique random ID generated for this session

var myId = Math.floor(100000*Math.random());

//Number of rows currently displayed

var rowCount;

function updateSocketStatus(message){

document.getElementById("socketStatus").innerHTML = message;

}

function updateGeolocationStatus(message){

document.getElementById("geoStatus").innerHTML = message;

}

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

updateSocketStatus("Update location data:" dataReturned(e.data));

}

}

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

}

function sendMyLocation(newLocation){

if(ws){

ws.send(newLocation)

}

}

function dataReturned(locationData){

var allData = JSON.parse(locationData);

var incomingId = allData[1];

var incomingLat = allData[2];

var incomingLong = allData[3];

var incomingRow = document.getElementById(incomingId);

if(!incomingRow){

incomingRow = document.getElementById("div");

incomingRow.setAttribute("id",incomingId);

incomingRow.userText = (incomingId == myId)?"Me":'User' rowCount;

rowCount ;

document.body.appendChild(incomingRow);

}

incomingRow.innerHTML = incomingRow.userText " \ Lat: "

incomingLat " \ Lon: "

incomingLong;

return incomingRow.userText;

}

function handleLocationError(error){

switch(error.code){

case 0:

updateGeolocationStatus("Error retrieving location information: " error.message);

break;

case 1:

updateGeolocationStatus("The user blocks access to location information.");

break;

case 2:

updateGeolocationStatus("The browser cannot detect your location information: " error.message);

break;

case 3:

updateGeolocationStatus("The browser timed out when retrieving location information.");

break;

}
}


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
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

See all articles

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools