Use HTML5 WebSocket to build real-time Web applications, html5websocket

Source: Internet
Author: User

[Switch] using HTML5 WebSocket to build real-time Web applications, html5websocket

Introduction and practice of HTML5 WebSocket

This article mainly introduces the principles of HTML5 WebSocket and its revolutionary innovation for real-time Web development. It also demonstrates the strength and ease of use of WebSocket through the case of a WebSocket server and client.

As the next-generation Web standard, HTML5 has many notable new features, such as Canvas, local storage, multimedia programming interfaces, WebSocket, and so on. Specifically, WebSocket, called "Web TCP", attracts the attention of developers. The emergence of WebSocket makes it possible for the browser to provide Socket support, thus providing a two-way channel based on TCP connection between the browser and the server. Web developers can easily use WebSocket to build real-time web applications. In this way, developers have become more powerful. This article first introduces the basic concepts of HTML5 WebSocket and the problems that this specification tries to solve, and then introduces the basic principles and programming interfaces of WebSocket. Next, we will use a simple case to demonstrate how to implement a WebSocket application, and demonstrate how WebSocket is perfectly unified in terms of powerful functions and easy-to-use programming. Finally, the status, limitations, and future prospects of mainstream browsers for WebSocket support are introduced.

Real-time Web application dilemma

The information interaction process of a Web application is usually when a client sends a request through a browser. After receiving and reviewing the request, the server processes the request and returns the result to the client. Then, the client browser displays the information, this mechanism is still safe for applications with less frequent information changes, but for applications with high real-time requirements, for example, online games, online securities, device monitoring, online news broadcast, and RSS subscription push. When the client browser prepares to present the information, the information may be outdated on the server. Therefore, keeping the client and server information synchronized is a key element of real-time Web applications, which is also a challenge for Web developers. Before the WebSocket specification came out, developers had to adopt some compromise solutions to implement these real-time Web applications. The most common ones were Polling and Comet technologies, the Comet technology is actually an improvement of the polling technology. It can be subdivided into two implementation methods: Long polling mechanism and stream technology. Below we will briefly introduce these technologies:

Round Robin:

This is the earliest solution to implement real-time Web applications. The client sends a request to the server at a certain interval, and maintains the synchronization between the client and the server in the form of frequent requests. The biggest problem with this synchronization solution is that when the client initiates a request to the server at a fixed frequency, the data on the server may not be updated, which will lead to a lot of unnecessary network transmission, therefore, this is a very inefficient real-time solution.

Long polling:

Long round robin improves and improves regular round robin to reduce invalid network transmission. When no data is updated on the server, the connection will be retained for a period of time until the data or status changes or the time expires. This mechanism can be used to reduce the interaction between invalid clients and servers. Of course, if the data on the server is frequently changed, this mechanism does not substantially improve performance compared with regular polling.

Stream:

The stream technology solution usually sends a persistent connection request to the server using a hidden window on the client page. The server responds to this request and constantly updates the connection status to ensure that the connection between the client and the server does not expire. This mechanism can continuously push server information to the client. This mechanism has a problem in user experience. You need to design different solutions for different browsers to improve the user experience. At the same time, when the concurrency is large, it is a great test for server resources.

Based on these solutions, you will find that the so-called real-time technologies we are currently using are not real-time technologies. They are just simulating real-time effects using Ajax, each interaction between the client and the server is an HTTP request and response process, and each HTTP request and response carries the complete HTTP header information, this increases the amount of data transmitted each time, and the client and server programming implementations in these solutions are complicated. In actual applications, in order to simulate real-time results, developers often need to construct two HTTP connections to simulate two-way communication between the client and the server. One connection is used to process data transmission from the client to the server, A connection is used to process data transmission from the server to the client, which increases programming complexity and server load, and restricts the scalability of the application system.

 

 

WebSocket rescue

HTML5 WebSocket is designed to replace the polling and Comet technologies so that the client browser can communicate with the desktop system in real time in a C/S architecture. The browser sends a WebSocket connection request to the server through JavaScript. After the connection is established, the client and the server can directly exchange data through the TCP connection. WebSocket connection is essentially a TCP connection. Therefore, compared with polling and Comet technologies, it has great performance advantages in terms of data transmission stability and data transmission volume. The Websocket.org website provides a detailed test and comparison of the traditional polling and WebSocket call methods, and implements a simple Web application using the polling and WebSocket methods respectively, here we reference their test result diagram:

Figure 1. network load comparison between polling and WebSocket implementation

This figure clearly shows that the WebSocket solution has a great performance advantage over the traditional Ajax polling solution when the traffic and load increase. This is why we think WebSocket is the preferred solution for real-time Web applications in the future.

 

 

WebSocket Specification

The WebSocket protocol is essentially a TCP-based protocol. To establish a WebSocket connection, the client browser must first initiate an HTTP request to the server. This request is different from the common HTTP request and contains some additional header information, including the additional header information."Upgrade: WebSocket"It indicates that this is an HTTP request for protocol upgrade. The server parses the additional header information and generates the response information and returns it to the client. The WebSocket connection between the client and the server is established, both parties can transmit information freely through this connection channel, and the connection will continue until a client or a server actively closes the connection.

Next we will introduce the WebSocket specification in detail. As this specification is still in the draft stage and the version changes rapidly, we chooseDraft-hixie-thewebsocketprotocol-76To describe the WebSocket protocol. This version is currently well supported in some mainstream browsers such as Chrome, FireFox, and Opera. If you are referring to a new version, the content may be slightly different.

The following is an example of a typical WebSocket request and response:

List 1. 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]

These 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 server can transmit data in two directions through this channel.

In the actual development process, in order to use the WebSocket interface to build a Web application, we first need to build a server that implements the WebSocket specification. The server implementation is not limited by the platform and development language, you only need to follow the WebSocket specifications. Some mature WebSocket Server implementations have emerged, such:

  • Kaazing WebSocket Gateway-a Java-implemented WebSocket Server
  • Mod_pywebsocket-a Python-implemented WebSocket Server
  • Netty-a Java-implemented network framework that includes support for WebSocket
  • Node. js-a Server-side JavaScript Framework provides support for WebSocket

If the preceding WebSocket server implementation does not meet your business needs, developers can implement a server according to the WebSocket specification. In the "WebSocket practice" section, we will use the C # language on the Microsoft. NET platform to create a simple WebSocket server, and then build a simple real-time chat system.

 

 

WebSocket JavaScript Interface

The previous section introduced the WebSocket specification, which mainly introduced the handshake protocol of WebSocket. The handshake protocol is usually a problem we need to consider when constructing a WebSocket server and providing WebSocket support for browsers. The WebSocket JavaScript client interface for Web developers is very simple, the following is the definition of WebSocket JavaScript interface:

List 2. WebSocket JavaScript Definition
 [Constructor(in DOMString url, in optional DOMString protocol)]  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 long bufferedAmount;    //networking    attribute Function onopen;    attribute Function onmessage;    attribute Function onclose;    boolean send(in DOMString data);    void close();  };  WebSocket implements EventTarget;

The URL attribute indicates the network address of the WebSocket server. The protocol is generally "ws". The send method is to send data to the server, and the close method is to close the connection. In addition to these methods, there are also important events: onopen, onmessage, onerror, and onclose. We borrowedNettutsThe following figure shows the WebSocket interface:

Figure 2. WebSocket JavaScript Interface

The following is a simple JavaScript code that shows how to establish a WebSocket connection and obtain data:

Listing 3. JavaScript code for an instance that establishes a WebSocket connection
 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) {  console.log('Error occured: ' + evt.data);  }
 

 

Browser support

The following shows the support of mainstream browsers for HTML5 WebSocket:

Browser Support
Chrome Supported in version 4 +
Firefox Supported in version 4 +
Internet Explorer Supported in version 10 +
Opera Supported in version 10 +
Safari Supported in version 5 +
 

 

WebSocket practice

This section uses a case to demonstrate how to use WebSocket to build a real-time Web application. This is a simple real-time multi-user chat system, including the implementation of the client and server. The client initiates a request to the chat server through a browser. The server parses the handshake request sent by the client and generates response information and returns it to the client, thus establishing a connection channel between the client and the server. The server supports the broadcast function. The information sent by each chat user is sent to all users in real time. When a user exits the chat room, the server needs to clear the connection information of the user, avoid resource leakage. We will demonstrate the implementation of the Web chat system from the server and client respectively. In terms of implementation, we adopt the C # language to implement the WebSocket server, the client is an HTML file running in the browser.

WebSocket server implementation

The implementation of this chat server is very similar to that of a socket-based network application. First, the server must start a socket to listen for connection requests from the client, the key difference is that the WebSocket server needs to parse the client's WebSocket handshake information and generate corresponding response information according to the requirements of the WebSocket specification. Once the WebSocket connection channel is established, the interaction between the client and the server is the same as that between common Socket network applications. Therefore, in the following description of WebSocket server implementation, we mainly explain how the WebSocket server processes the WebSocket handshake information. As for the establishment of the WebSocket listening port and the reading and writing of the socket information stream, there are some common socket programming methods, so we will not explain them more. You can refer to the source code file in this article.

When describing the WebSocket specification, it is mentioned that a typical WebSocket Upgrade information is as follows:

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]

The Sec-WebSocket-Key1, Sec-WebSocket-Key2, and [8-byte security key] header information is the source of the WebSocket server used to generate the response information, accordingDraft-hixie-thewebsocketprotocol-76According to the definition of the draft, the WebSocket server generates correct response information based on the following algorithms:

  1. One character reads the value in the Sec-WebSocket-Key1 header information one by one, Concatenates the numeric character into a temporary string, and counts the number of all spaces;
  2. Convert the numeric string generated in step 1 to an integer number, and then divide it by the number of spaces calculated in step 2 to convert the resulting floating point number to an integer;
  3. Convert the integer value generated in step 1 to a network byte array that conforms to network transmission;
  4. Perform steps 1st to 3rd on the Sec-WebSocket-Key2 header information to obtain another network byte array;
  5. Combine the [8-byte security key] and the network byte array generated in step 3rd and step 4th into a 16-byte array;
  6. Generate a hash value for the byte array generated in step 1 using the MD5 algorithm. The hash value is returned to the client as a security key, indicating that the server obtains the client request and agrees to create a WebSocket connection.

So far, the client and the server's WebSocket handshake are complete, and the WebSocket channel is also established. The following describes how to generate a network byte array based on the handshake information transmitted by the server .. The NET platform provides convenient functions for string, value, and Array Operations. Therefore, the method for generating byte arrays is very simple and clear. The Code is as follows:

Listing 4. Code for generating a network byte array
    private byte[]   BuildServerPartialKey(string clientKey)  {       string partialServerKey = "";      byte[] currentKey;      int spacesNum = 0;      char[] keyChars = clientKey.ToCharArray();      foreach (char currentChar in keyChars)      {          if (char.IsDigit(currentChar)) partialServerKey += currentChar;         if (char.IsWhiteSpace(currentChar)) spacesNum++;      }      try      {               currentKey = BitConverter.GetBytes((int)(Int64.Parse(partialServerKey)  / spacesNum));         if (BitConverter.IsLittleEndian) Array.Reverse(currentKey);      }      catch      {         if (currentKey!= null) Array.Clear(currentKey, 0, currentKey.Length);      }      return currentKey;   }

After obtaining the network byte array, the server can generate a 16-bit security key as follows:

Listing 5. Code for generating a 16-bit security key
 private byte[] BuildCompleteServerKey(byte[] serverKey1, byte[] serverKey2,  byte[] last8Bytes)  {      byte[] concatenatedKeys = new byte[16];     Array.Copy(serverKey1, 0, concatenatedKeys, 0, 4);     Array.Copy(serverKey2, 0, concatenatedKeys, 4, 4);     Array.Copy(last8Bytes, 0, concatenatedKeys, 8, 8);     System.Security.Cryptography.MD5 MD5Service =  System.Security.Cryptography.MD5.Create();    return MD5Service.ComputeHash(concatenatedKeys);  }

The entire implementation is very simple and clear, is to combine the generated network byte array and the [8-byte security key] in the header information submitted by the client into a 16-byte array and use the MD5 Algorithm for encryption, then, the generated security key is returned to the client as the response information, and the WebSocekt connection channel between the two parties is established. The WebSocket handshake information processing logic is implemented, and a WebSocket server with basic functions is complete. The entire WebSocket server consists of two core classes: WebSocketServer and SocketConnection. For the sake of space, we will not introduce the attributes and methods of each class, the attachment of the article provides detailed source code. If you are interested, you can refer to it.

When the server is started, the following figure is displayed:

Figure 3. WebSocket server startup Screen

The client can enter the connection address of the chat server based on this information. When a client is connected to the chat server, the server will print the handshake information between the client and the server, the chat information of each customer is displayed on the server interface. The running chat server interface is as follows:

Figure 4. A client connected to the WebSocket Server

We briefly describe the most basic elements for implementing a WebSocket server. The implementation of the client is described in the next section.

Client implementation

The implementation of the client is much simpler than the implementation of the server. We only need to design the HTML user interface as expected, and then call the WebSocket JavaScript interface to interact with the WebSocket server. Of course, don't forget to use a browser that supports HTML5 and WebSocket. the browser used when I wrote this article is Firefox. The Page Structure of the client is very concise. The initial running interface is as follows:

Figure 5. Chat Room client initial Page

When the page is loaded for the first time, it first checks whether the current browser supports WebSocket and provides the corresponding prompt information. When you press the connection button, a WebSocekt connection to the chat server will be initialized on the page. After the initialization is successful, the corresponding WebSocket event processing function will be loaded on the page. The client JavaScript code is as follows:

Listing 6. Code for initializing the client WebSocket object
Function ToggleConnectionClicked () {if (SocketCreated & (ws. readyState = 0 | ws. readyState = 1) {ws. close ();} else {Log ("ready to connect to the chat server... "); try {ws = new WebSocket (" ws: // "+ document. getElementById ("Connection "). value); SocketCreated = true;} catch (ex) {Log (ex, "ERROR"); return;} document. getElementById ("ToggleConnection "). innerHTML = "disconnected"; ws. onopen = WSonOpen; ws. onmessage = WSonMess Age; ws. onclose = WSonClose; ws. onerror = WSonError ;}}; function WSonOpen () {Log ("the connection has been established. "," OK "); $ (" # SendDataContainer "). show ("slow") ;}; function WSonMessage (event) {Log (event. data) ;}; function WSonClose () {Log ("Connection closed. "," ERROR "); document. getElementById ("ToggleConnection "). innerHTML = "connection"; $ ("# SendDataContainer "). hide ("slow") ;}; function WSonError () {Log ("WebSocket error. "," ERROR ");};

When you press the send button, the client will call the WebSocket object to send information to the server, and the message will be broadcast to all users. The implementation code is as follows:

Function SendDataClicked () {if (document. getElementById ("DataToSend"). value! = "") {Ws. send (document. getElementById ("txtName "). value + "Description: \" "+ document. getElementById ("DataToSend "). value + "\" "); document. getElementById ("DataToSend "). value = "";}};

If multiple users log on to the chat server, the running effect of the client page is as follows:

Figure 6. Chat client running page

So far, we have completed a complete WebSocket client implementation. Users can experience the simplicity and efficiency of this chat room without considering page refresh and tedious Ajax calls, enjoy the user experience of desktop programs. The strength and ease of use of WebSocket are evident. You can add more functions on this basis to design a more beautiful user interface and experience the strength of WebSocket. For complete client code, see the source code provided in the attachment.

 

 

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.

 

 

Summary

This article introduces the emergence of HTML5 WebSocket and the problems it tries to solve. Then it introduces the WebSocket specifications and WebSocket interfaces, as well as the performance advantages compared with the traditional real-time technology, it also demonstrates how to use WebSocket to build a real-time Web application. Finally, we introduce the support of HTML5 by mainstream browsers and the limitations of WebSocket. However, we should see that although HTML5 WebSocket still has some limitations, it is already the trend of the times. Microsoft also clearly expressed its support for HTML5 in the future, we can see these support in Windows 8 and IE10, and we also see HTML5 and WebSocket on various mobile devices and tablets. WebSocket will become a new force for real-time Web application development in the future. As a Web developer, it is no suspense to pay attention to HTML5 and WebSocket, otherwise, we can only look at the new wave of software innovation.

 
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.