HTML5 WebSocket protocol for building real-time WEb applications

Source: Internet
Author: User

HTML5 WebSocket protocol for building real-time WEb applications

We have mentioned so many theories before. Let's look at code learning.

First, let's look at a simple javascript code that calls the WebSockets API.
var ws = new WebSocket(“ws://echo.websocket.org”);  ws.onopen = function(){ws.send(“Test!”); };  ws.onmessage = function(evt){console.log(evt.data);ws.close();};  ws.onclose = function(evt){console.log(“WebSocketClosed!”);};    ws.onerror = function(evt){console.log(“WebSocketError!”);};
There are only five lines of code in total. Now, we will give a brief overview of the significance of these five lines of code.
The first line of code is to apply for a WebSocket object. The parameter is the address of the server to be connected. It is the same as that of http starting with http: //. the URL of WebSocket uses ws: //. In addition, the secure WebSocket protocol starts with wss.

From the second row to the fifth row, the WebSocket object registers the message processing function. The WebSocket object supports four messages: onopen, onmessage, onclose, and onerror. When the Browser and WebSocketServer are connected successfully, the onopen message is triggered; if the connection fails, the message sending or receiving data fails, or the processing data fails, the browser triggers the onerror message. When the Browser receives the data sent by the WebSocketServer, The onmessage is triggered, the evt parameter contains the data transmitted by the server. When the Browser receives a closed connection request sent by the WebSocketServer, The onclose message is triggered. We can see that all operations are triggered by messages, so that the UI will not be blocked, so that the UI has a faster response time and a better user experience.

This is the complete code:

 

// JavaScript code var wsServer = 'ws: // localhost: 8888/demo' for an instance that establishes a WebSocket connection; var websocket = new WebSocket (wsServer); websocket. onopen = function (evt) {onOpen (evt)}; websocket. onclose = function (evt) {onClose (evt)}; websocket. onmessage = function (evt) {onMessage (evt)}; websocket. onerror = function (evt) {onError (evt)}; function onOpen (evt) {console. log ("Connected to WebSocket server. ");} function onClose (evt) {console. log ("Disconnected");} function onMessage (evt) {console. log ('retrieved data from server: '+ evt. data);} function onError (evt) {console. log ('error occured: '+ evt. data );}

 

A typical example of WebSocket request initiation and response looks as follows: WebSocket handshake protocol (client-to-server)
GET /demo HTTP/1.1 Host: example.com Connection: Upgrade Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 Upgrade: WebSocket Sec-WebSocket-Key1: 4@1 46546xW%0l 1 5 Origin: http://example.com [8-byte security key] 
Server to client:
HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade WebSocket-Origin: http://example.com WebSocket-Location: ws://example.com/demo [16-byte hash response]
It can be seen that these WebSocket requests are similar to common HTTP requests, but some of them are closely related to the WebSocket protocol. We need to briefly introduce these requests and response information. "Upgrade: WebSocket" indicates that this is a special HTTP request, the purpose of the request is to upgrade the communication protocol between the client and the server from HTTP to WebSocket. The information requested from the client to the server contains header information such as the Sec-WebSocket-Key1, Sec-WebSocket-Key2, and [8-byte securitykey. This is the handshake information that the client browser needs to provide to the server. The server parses the header information and generates a 16-bit security key based on the handshake information and returns it to the client, to indicate that the server obtains the client request and agrees to create a WebSocket connection. Once the connection is established, the client and the server can transmit data in two directions through this channel (this is the time when data is transmitted over TCP, eliminating the need for data header data transmission ).
To build a WebSocket Server, if we want to build a Web Server, we will have a lot of choices, and there are also many mature products available for our applications on the market, such as open-source Apache, after installation, you only need simple configuration (or default configuration) to work. However, it is not that easy to build a WebSocket server, because WebSocket is a new communication protocol and is still draft and has not become a standard, there is no mature WebSocket server or Library to implement the WebSocket protocol on the market, so we have to write code to parse and assemble WebSocket data packets. To complete a WebSocket server in this way, it is estimated that all people want to give up. Fortunately, there are several good open source libraries on the market for us to use, such as PyWebSocket, WebSocket-Node, libWebSockets, etc. These library files have implemented the encapsulation and resolution of WebSocket data packets. We can call these interfaces, which greatly reduces our workload.
The following is a brief introduction to these open source library files.
1. PyWebSocket
PyWebSocket is written in Python. It can be easily expanded across platforms. Currently, WebKit uses it to build a WebSocket server for LayoutTest.
We can get the source code through the following command
Svncheckouthttp: // pywebsocket.googlecode.com/svn/trunk/ pywebsocket-read-only
For more information, see http://code.google.com/p/pywebsocket.
2. WebSocket-Node
WebSocket-Node is written in JavaScript language. This library is built on nodejs. If you are familiar with JavaScript, refer to it. In addition, Html5 and Web applications are becoming more and more popular, nodejs is also receiving widespread attention.
We can get the source code from the connection below
Https://github.com/Worlize/Websocket-Node
3. LibWebSockets
LibWebSockets is written in C/C ++ language and can be customized more vigorously. From TCP listening to packet completion, we can all participate in programming.
We can obtain the source code from the following command:

Git clone git: // git.warmcat.com/libwebsockets

 

Limitations of WebSocket the advantages of WebSocket have been listed many times. However, as an evolving Web specification, we also need to see some risks of using Websocket to build applications. First of all, the WebSocket specification is still in the draft stage, that is, its specification and API are still subject to changes. Another risk is that Microsoft's IE is the largest browser in the market, compared with other mainstream browsers, HTML5 support is relatively poor, which is a problem we must consider when building enterprise-level Web applications.

 

Because I have no intention of seeing the introduction of the WebSocket protocol, I feel that it is indeed a breakthrough in technology and it is necessary to study it. Although HTML5 WebSocket has some limitations at present, it is already the trend of the times. Microsoft also clearly expresses its support for HTML5 in the future, and we can see these support in Windows 8 and IE10, we also saw HTML5 and WebSocket on various mobile devices and tablets. WebSocket will become a new force for real-time Web application development in the future. Although it is not a Web developer, it is no suspense to pay attention to HTML5 and pay attention to WebSocket, otherwise, we can only look at the new wave of software innovation.

 

Learning connection: http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/

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.