The HTML5 server provides various solutions for pushing messages.

Source: Internet
Author: User

The HTML5 server provides various solutions for pushing messages.
Summary

In applications of various BS architectures, the server usually needs to actively push various messages to the client to receive notifications similar to emails, messages, and to-do items.

The problem with the BS architecture is that the server always uses a Q & A mechanism. This means that if the client does not actively send messages to the server, the server will not be able to know how to push messages to the client.

With the development of various technologies and standards such as HTML and browsers, different methods and methods are generated in turn to enable the server to actively push messages. They are AJAX, Comet, ServerSent, and WebSocket.

This article will explain the various technical methods mentioned above in a straightforward manner.

AJAX

A normal page works like this in a browser:

When the user clicks any <a> on the website or triggers any <form> submission:

What we can hardly find is that once a connection is established, the page cannot be maintained. The whole process looks a little strong. Maybe I only need a cup of New Cola, but you have to give me a full package combination.

Now let's take a look at the XmlHttpRequest component. This component allows us to manually create an HTTP request to send the desired data, and the server can only return the expected results. The biggest benefit is that, when we receive a response from the server, the original page is not destroyed. This is like shouting "I have finished my coffee and I want to renew my cup". Then the waiter will take a cup of coffee instead of dumping all the packages I have not finished.

When we use AJAX to implement server push, the client keeps asking the server "Is there any message for me? ", Then the server answers" yes "or" no "to achieve the effect. Its implementation method is also very simple, and AJAX calls encapsulated by the jQuery framework are also very convenient:

Function getMessage (fn) {$. ajax ({url: "Handler. ashx ", // a page ype:" text ", // response type, which can be JSON, XML, and Other types:" get ", // HTTP request type, which can also be post success: function (d, s) {fn (d); // when a normal response is received, the callback function is used to notify the external server }, complete: function (x, s) {setTimeout (function () {getMessage (fn) ;}, 5000); // no matter whether the response succeeds or fails, ask the server again several seconds later }});}

The above code can be used to check whether the server has any message to process every five seconds. In this way, the push effect can be achieved, but there is a problem:

Strictly speaking, this practical method is not a real server that actively pushes messages. However, due to the lack of early technical means, AJAX round robin has become a common method.

 

 

 

Comet

We know that HTTP requests are actually implemented based on TCP connections. Let's look at the HTTP request processing process described earlier:

When we see this process, we can easily think of it. If we save Step 1-close the connection, isn't there a long connection that has been maintained. Through some operations on the server, we can directly send data from this TCP connection to the client.

With this technology, we can greatly improve the real-time performance of server pushing, and reduce the overhead caused by the constant establishment and cast of connections on the server.

Currently, there are many AJAX-based Comet mechanisms on the market, but there are two main methods:

 

 

 

Server-Sent

Server-Sent is a standard proposed by HTML5. It uses the Comet idea and standardizes it. So that the technology of Comet was transformed from the original branch Derivative Technology to the official standard of orthodox.

It works in the same way as Comet. The client initiates a TCP connection with the server, and then maintains the connection, serverSent uses the "Q" + "Answer" mechanism. After the connection is created, the browser periodically sends the message to the server to check whether the server has its own message.

This standard not only requires that the supported browsers can create persistent connections with servers in the original ecology, but also requires the uniformity of JavaScript scripts, this allows browsers with the same set of code to complete Server-Sent coding.

The creation code is very simple:

// Define a ServerSent object var s = new EventSource ("Handler. ashx "); // The callback function s when a non-Custom Event is received. onmessage = function (e) {alert (e. data) ;}; // callback function s when receiving a message named MyEvent by the server. addEventListener ("MyEvent", function (e) {alert (e. data );});

The server code is also very simple:

Public class Handler: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/event-stream"; context. response. expires =-1; context. response. write ("event: MyEvent \ r \ n"); // event type. Use \ r \ n to end context. response. write ("data: HelloWorld! \ R \ n "); // event data, use \ r \ n when changing the line, and add data: context to the new line. response. write ("data: I'm server! \ N "); // end event data, use \ n context. response. flush (); // The End cannot be used here; otherwise, the connection is closed.} public bool IsReusable {get {return true ;}}}

Two short pieces of code already have Server Message push.

In general, SeverSent is the Comet under the HTML5 specification, which has better uniformity and is simple and easy to use.

 

 

 

 

WebSocket

You can see the name. This is a Socket connection that can be used in a browser.

This is also an HTML5 standard. He asked the browser to manually create a TCP connection through a JavaScript script to communicate with the server.

WebSocket does not contain many additional functions. It only includes the basic functions of TCP connections: creation, temporary, and sending.

In addition, WebSocket uses the ws and wss protocols. The server must have a handshake algorithm to open the connection.

Therefore, compared with the previous methods, WebSocket has the largest encoding capacity, but it can freely implement all possible functions because it has no other restrictions.

That is, it can meet the "Q" + "Answer" response mechanism, or implement the active push function.

Like ServerSent, HTML5 also standardizes the JavaScript called by WebSocket. We can use a very simple code to build a WebSocket connection.

Var ws = new WebSocket ("ws: // 192.168.0.105: 10080"); // connect to the server ws. onopen = function (event) {alert ("Connection established with server \ r \ n current connection status:" + this. readyState) ;}; ws. onmessage = function (event) {alert ("received data from the server: \ r \ n" + event. data) ;}; ws. onclose = function (event) {alert ("disconnected from server \ r \ n current connection status:" + this. readyState) ;}; ws. onerror = function (event) {alert ("WebSocket exception! ");};

You can also send messages by sending them.

ws.send("Hello World");

WebSocket has complicated protocols and requires additional programming on the server side for data communication. For details about the agreement, I will explain it in a later article.

 

WebSocket + MessageQueue

MessageQueue, MQ for short, is the message queue. It is a technology that is often used on the Tcp server. By producing and accessing various message types, the MQ server sends messages generated by the producer to clients of interest. There are many MQ frameworks on the market, such as ActiveMQ.

ActiveMQ already supports the WebSocket protocol, which means that WebSocket can be connected to the MQ server as a producer or consumer.

Developers can connect to the MQ server through the JS script of MQTT, and connect the Web server to the MQ server. Thus, they can end up with the Http Communication Protocol and use Socket communication to complete data exchange.

 

 

Summary:

In general, we recommend using ServerSent and WebSocket to push server messages under the HTML5 standard.

Compare the two methods.

The ServerSent method can make the server development still follow the previous method, but it works in a similar way as Comet.

The WebSocket method has a high requirement on server development, but it works in full push mode.

I actually prefer WebSocket + MQ, but it is better to use SeverSent for the renovation of old projects.

 

End

This article is original author, reproduced please indicate the source: http://www.cnblogs.com/ShimizuShiori/p/5464063.html

The relevant code in the article can be viewed in the ServerSent directory in the http://j.zizhusoft.com/Develop/Explorer.aspx

 

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.