This article mainly studies the use of HTML5WebSockets, 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. HTML5WebSockets can reduce the data size from several thousand bytes to two bytes, and reduce the latency from ms to 50 ms. It is perfect for the current implementation of real-time Web applications, most of them focus 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:
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
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 ");
}
Geo. watchPosition (updateLocation, handleLocationError, {maximumAge: 20000}); // update every 20 s
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:
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
Script
// WebSocket reference
Var ws;
// Unique random ID generated for this session
Var myId = Math. floor (100000 * Math. random ());
// The number of currently displayed rows
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 ("HTML5 Geolocation supported by browsers ");
}
Geo. watchPosition (updateLocation, handleLocationError, {maximumAge: 20000}); // update every 20 s
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 );
}
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 ("p ");
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 ("retrieval location information error:" + error. message );
Break;
Case 1:
UpdateGeolocationStatus ("the user stops obtaining location information. ");
Break;
Case 2:
UpdateGeolocationStatus ("the browser cannot detect your location information:" + error. message );
Break;
Case 3:
UpdateGeolocationStatus ("the browser's retrieval Location Information Times out. ");
Break;
}
}
Script