Detailed learning example of html5 websockets full-duplex communication

Source: Internet
Author: User

Comments: This article mainly studies the use of HTML5 WebSockets, which is the most powerful communication function in HTML5. It defines a full-duplex communication channel and can communicate with only one Socket on the Web, this reduces unnecessary network traffic and network latency. HTML5 WebSockets can reduce the data size from several kilobytes to two bytes, reduce the latency from ms to 50 ms, and perfect

Currently, the implementation of real-time Web applications is mostly based on polling and other server push technologies, among which Comet is the most famous. The Comet technology allows the server to actively push data to the client asynchronously.

When polling is used, the browser regularly sends HTTP requests and then receives responses. When long polling is used, the browser sends a request to the server, which will keep it open for a period of time; when using the stream solution, the browser will send a complete HTTP request, but the server will send and keep a open response, which is continuously updated and open for an indefinite period of time.

The preceding three methods involve HTTP request headers and Response Headers when sending real-time data, and contain a large amount of additional and unnecessary header data, resulting in transmission latency.

I. interpreting HTML5 WebSockets

1. WebSocket handshake

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 the server in full duplex mode.

Note: In the network, each message starts with 0x00 bytes and ends with 0 x ff, the intermediate data is in UTF-8 encoding format.

2. WebSocket Interface

In addition to the WebSocket protocol, WebSocket interfaces for JavaScript applications are also defined.

The Code is as follows:
Interface WebSocket {
Readonly attribute DOMString URL;
// Ready
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: ws: // and wss: // prefix indicate WebSocket connection and secure WebSocket connection respectively.

Ii. HTML5 WebSockets API

This section describes how to use HTML5 WebSockets.

1. Check whether the browser supports

Use window. WebSocket to determine whether the browser supports this function.

2. Basic API usage

A. Create a WebSocket object and connect it to the WebSocket Server


The Code is as follows:
Url = "ws: // localhost: 8080/echo ";
Ws = new WebSocket (url );

B. Add an event listener.

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

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


The Code is as follows:
Ws. onopen = function (){
Log ("open ");
}
Ws. onmessage = function (){
Log (e. data );
}
Ws. onclose = function (){
Log ("closed ");
}

C. Send messages

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

Ws. send ("Hello World ");

Iii. HTML5 WebSockets application example

This section uses the Geolocation interface described above to create an application that calculates the distance directly on the Web page.

1. Compile HTML files


The Code is as follows:
<! DOCTYPE html> </p>

2. Add WebSocket 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


The Code is as follows:
Var geo;
If (navigator. geolocation ){
Geo = navigator. geolocation;
UpdateGeolocationStatus ("HTML5 Geolocation supported by browsers ");
} </P> <p> geo. watchPosition (updateLocation, handleLocationError, {maximumAge: 20000}); // update every 20 S </p> <p> function updateLocation (position ){
Var latitude = position. coords. latitude;
Var longpolling = position. coords. longpolling;
Var timestamp = position. timestamp;
UpdateGeolocationStatus ("location update time:" + timestamp );
Var toSend = JSON. stringify ([myId, latitude, longpolling]);
SendMyLocation (toSend );
}

4. merge all contents


The Code is as follows:
<! DOCTYPE html> </p> } </P> </script> </p>


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.