HTML5 programming journey Series 3: Analysis of WebSockets Technology

Source: Internet
Author: User

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 thousand bytes to two bytes, reduce the latency from ms to 50 ms, and eliminate the traditional Comet and Ajax round robin (polling) and long-polling (long-polling) perfectly) and streaming solutions.

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.

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;

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

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

The above two lines of code can also be merged into one line of code:

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

  

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.

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

<! DOCTYPE html> 

  

2. Add WebSocket code

Function loadDemo () {// make sure that the browser supports WebSocketif (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

Var geo; if (navigator. geolocation) {geo = navigator. geolocation; updateGeolocationStatus ("HTML5 Geolocation supported by browsers");} geo. watchPosition (updateLocation, handleLocationError, {maximumAge: 20000}); // function updateLocation (position) {var latitude = position every 20 s. 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

<! DOCTYPE html> 

Note: The above Code requires the support of an additional server. Here, we will attach the server file written in Python provided in the original book. For details about how to run Python, refer to other information on the Internet.

Link: http://www.cnblogs.com/oooweb/p/html5-websockets-tutorials.html

Via ocshina

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.