HTML5 WebSocket protocol < two > based on building real-time Web applications

Source: Internet
Author: User
Tags git clone

With so many theories in front, let's take a look at code learning.

Websocketapi Introductionfirst 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!");};
This code is only 5 lines in total, and now briefly outlines the meaning of these 5 lines of code.
The first line of code is to request a WebSocket object, the parameter is the server-side address that needs to be connected , the same as the HTTP protocol using//, the URL of the WebSocket protocol starts with ws://, Additionally the secure WebSocket protocol starts with wss://.

The second line to the fifth behavior WebSocket object Registration Message handler function,WebSocket object altogether supports four messages OnOpen, OnMessage, OnClose and OnError, The OnOpen message is triggered when the browser and Websocketserver connections are successful, and browser triggers a onerror message if the connection fails, the data fails to be sent, or the data is processed with an error. The onmessage message is triggered when browser receives the data sent by Websocketserver, and the parameter evt contains the data transmitted by the server. The OnClose message is triggered when browser receives a close connection request sent by the Websocketserver side. We can see that all actions are triggered by the message, so that the UI is not blocked, and the UI has a faster response time and a better user experience.

This is the complete code:

Create an instance of the WebSocket connection JavaScript code var  wsserver = ' Ws://localhost:8888/demo '; 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) {   cons Ole.log (' Error occured: ' + evt.data); }

An example of a typical WebSocket initiating request and getting a response looks like this:WebSocket Handshake Protocol (client-to-server)
Service-to-client:
http/1.1 101 WebSocket Protocol handshake upgrade:websocket Connection:upgrade websocket-origin:http://example.com Web Socket-location:ws://example.com/demo [16-byte Hash response]
It can be seen that these WebSocket requests are similar to the usual HTTP requests, but some of them are closely related to the WebSocket protocol. We need a brief introduction to these requests and responses,"Upgrade:websocket" means that this is a special HTTP request , and the purpose of the request is to upgrade the client and server-side communication protocols from the HTTP protocol to the WebSocket protocol. The information from the client-to-server request contains header information such as "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 side , the server side resolves the header information, generates a 16-bit security key and returns it to the client during the handshake, to indicate that the server has obtained the client's request and agrees to create a WebSocket connection. Once the connection is established, both the client and the server can transmit the data in two directions via this channel (this is the TCP transmission of data, eliminating the data transfer ).
Building WebSocket ServerIf we want to build a Web server, we will have a lot of choices, there are many mature products in the market for our application, such as open-source Apache, after installation only simple configuration (or the default configuration) can work. But it's not that easy if you want to build a websocket server, becauseWebSocket is a new communication protocol, is still a draft, does not become a standard, the market is not mature WebSocket server or library implementation WebSocket Protocol, we have to write our own code to parse and assemble websocket packets. To complete a websocket server, it is estimated that all people want to give up, fortunately, there are several good open source libraries in the market for us to use, such aspywebsocket,websocket-node,libwebsocketsAnd so on, these library files have implemented the encapsulation and parsing of websocket packets, we can call these interfaces, which greatly reduces our workload.
Here is a brief introduction to these open Source library files.
1. Pywebsocket
Pywebsocket written in Python language, can be very good cross-platform, expansion is also relatively simple, at present WebKit use it to build WebSocket server to do layouttest.
We can get the source code through the following command
Svncheckouthttp://pywebsocket.googlecode.com/svn/trunk/pywebsocket-read-only
More detailed information can be obtained from http://code.google.com/p/pywebsocket/.
2. Websocket-node
Websocket-node written in JavaScript language, this library is built on the Nodejs, for the familiarity of JavaScript friends can refer to, in addition HTML5 and Web applications are becoming more popular, Nodejs is also being widely watched.
We can get the source code from the link below
Https://github.com/Worlize/Websocket-Node
3. Libwebsockets
Libwebsockets is written in C + + language, can be customized more aggressively, from the beginning of the TCP monitoring to the completion of the package we can participate in programming.
We can get the source code from the following command

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

Limitations of WebSocketThe advantages of WebSocket have been enumerated a lot, but as an evolving WEB specification, we also want to see some of the risks of building applications with WebSocket today. First, the WebSocket specification is still in the draft phase, that is, its specifications and APIs are still possible , another risk is that Microsoft's IE as the largest market share of the browser, and other mainstream browser compared to the HTML5 support is relatively poor, This is one of the things we have to consider when building enterprise-class WEB applications.

Summarybecause inadvertently saw the introduction of the WebSocket protocol, I think technically is a breakthrough, it is necessary to learn. Although HTML5 WebSocket has some limitations, it is a general trend, Microsoft has clearly expressed the future of HTML5 support, and these support we can see in Windows 8 and IE10, we also on a variety of mobile devices, tablets see HTML5 and WebSocket's figure. WebSocket will become the future development of real-time WEB application of the new force should be no suspense, although not Web developers, but attention to HTML5, attention WebSocket should also put on the agenda, otherwise we in the new wave of software innovation can only do Howard.

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

HTML5 WebSocket protocol < two > based on building real-time Web applications

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.