Reverse Ajax Implementation _ajax

Source: Internet
Author: User
Tags error handling html tags mixed script tag setinterval
Reverse Ajax, part 1:introduction to Comet in the past few years, web development has changed a lot. Today, we expect to be able to access applications quickly and dynamically through the web. In this new article series, we learned how to use reverse Ajax (Reverse Ajax) technology to develop event-driven Web applications to achieve a better user experience. The client example uses the jquery JavaScript library, and in this first article we explore different reverse Ajax techniques, using downloadable examples to learn the comet of the stream (streaming) method and the long polling (polling) method.

Objective

Web development has made a lot of progress over the past few years, and we've gone way beyond linking static Web pages, which can cause browsers to refresh and wait for the page to load. What is needed now is a fully dynamic application that can be accessed via the web, which usually needs to be as fast as possible to provide nearly real-time components. In this new five-part article series, we learn how to use reverse Ajax (Reverse Ajax) technology to develop event-driven Web applications.

In this first article, we want to learn about reverse Ajax, polling (polling), streaming (streaming), comet, and long polling (length polling), learn how to implement different reverse Ajax communication technologies, and explore the pros and cons of each approach. You can download the corresponding source code for the example in this article.

Ajax, reverse Ajax, and WebSocket

Asynchronous JavaScript and XML (asynchronous JavaScript and Xml,ajax), a feature of browser functionality that can be accessed via JavaScript, It allows the script to send an HTTP request to the Web site behind the scenes without reloading the page. Ajax has been around for more than a decade, although its name contains XML, you can almost pass anything in an AJAX request, the most commonly used data is JSON, which is close to JavaScript syntax and consumes less bandwidth. Listing 1 shows an example of an AJAX request to retrieve a name from a local zip code.

Listing 1. Ajax request example var url = ' http://www.geonames.org/postalCodeLookupJSON?postalcode= '
+ $ (' #postalCode '). Val () + ' &country= '
+ $ (' #country '). Val () + ' &callback=? ' ;
$.getjson (URL, function (data) {
$ (' #placeName '). Val (data.postalcodes[0].placename);
});

In the downloadable source code in this article, you can see the role of this example in listing1.html.

Reverse Ajax (Reverse Ajax) is essentially the concept of being able to send data from the server side to the client. In a standard HTTP AJAX request, the data is sent to the server side, and reverse Ajax can simulate an AJAX request in some specific way, which is discussed in this article, so that the server can send events to the client as quickly as possible (low latency traffic).

WebSocket technology comes from HTML5, a technology that has recently emerged and has been supported by many browsers (Firefox, Google Chrome, Safari, etc.). WebSocket enables a two-way, Full-duplex communication channel that opens the connection through some HTTP request called the WebSocket handshake and uses a special header. The connection remains active, and you can use JavaScript to write and receive data, just as if you were using an original TCP socket interface. WebSocket in the second part of the article series.

Reverse Ajax Technology

The purpose of reverse Ajax is to allow server-side push information to the client. Ajax requests are stateless by default, and can only be made from the client to the server side. You can circumvent this limitation by using technology to simulate responsive communication between server-side and client.

HTTP Polling and Jsonp polling

Polling (polling) involves sending a request from the client to the server to get some data, which is clearly a purely Ajax HTTP request. In order to get server-side events as quickly as possible, the polling interval (two times between requests) must be as small as possible. But there is a drawback: if the interval is reduced, the client browser makes more requests, many of which do not return any useful data, which will waste bandwidth and processing resources.

The timeline in Figure 1 illustrates that some polling requests are made by the client, but no information is returned, and the client must wait until the next poll to get the two server-side events.

Figure 1. Reverse Ajax using HTTP polling

Jsonp polling is basically the same as HTTP polling, where the difference is that JSONP can emit cross-domain requests (not requests within your domain). Listing 1 uses JSONP to get a place name from a postal code, which is typically recognized by its callback parameters and the return content, which is executable JavaScript code.

To implement polling in JavaScript, you can use setinterval to periodically issue AJAX requests, as shown in Listing 2:

Listing 2. JavaScript Polling setinterval (function () {
$.getjson (' Events ', function (events) {
Console.log (events);
});
}, 2000);

The polling demo in the source code shows the bandwidth consumed by the polling method is small, but you can see that some requests do not return events, listing 3 shows the output of this polling sample.

Listing 3. Poll Demo example output [client] checking for events ...
[Client] No event
[Client] checking for events ...
[Client] 2 events
[Event] At Sun June 15:17:14 EDT 2011
[Event] At Sun June 15:17:14 EDT 2011
[Client] checking for events ...
[Client] 1 events
[Event] At Sun June 15:17:16 EDT 2011

Advantages and disadvantages of polling implemented with JavaScript:

1. Advantages: Easy to implement, does not require any server-side specific features, and in all browsers can work.

2. Disadvantage: This method is rarely used because it is completely not scalable. Consider the amount of bandwidth and resources lost when 100 clients each send out a 2-second polling request, in which case 30% requests do not return data.

Piggyback

The piggyback polling is a smarter approach than polling because it removes all non-essential requests (those that do not return data). There is no time interval and the client sends the request to the server when needed. The difference is that on the part of the response, the response is divided into two parts: the response to the request data and the response to the server event, if any part of it occurs. Figure 2 shows an example.

Figure 2. Reverse Ajax using piggyback polling

When implementing piggyback technology, it is common for all AJAX requests on the server side to return a mixed response, and there is an implementation example in the download for the article, as shown in Listing 4 below.

Listing 4. Piggyback code example $ (' #submit '). Click (function () {
$.post (' Ajax ', function (data) {
var valid = Data.formvalid;
Handling Validation Results
Then process other parts of the response (events)
Processevents (data.events);
});
});

Listing 5 shows some piggyback output.

Listing 5. Piggyback output example [client] checking for events ...
[Server] form valid? True
[Client] 4 events
[Event] At Sun June 16:08:32 EDT 2011
[Event] At Sun June 16:08:34 EDT 2011
[Event] At Sun June 16:08:34 EDT 2011
[Event] At Sun June 16:08:37 EDT 2011

You can see the results of the form validation and the events attached to the response, as well as the advantages and disadvantages of this approach:

1. Advantages: There is no request to return data, because the client has control over when to send the request, less consumption of resources. This method is also available on all browsers and does not require special features on the server side.

2. Disadvantages: When the cumulative server-side event needs to be routed to the client, you don't know anything about it, because it requires a client behavior to request them.

Comet

Reverse Ajax, which uses polling or a piggyback, is very restrictive: it is not scalable and does not provide low latency traffic (as soon as the event arrives on the server side, they reach the browser end at the fastest speed). Comet is a Web application model in which requests are sent to the server and maintain a long lifetime until a timeout or server-side event occurs. After the request is complete, another long lifetime Ajax request is sent to wait for another server-side event. With comet, the Web server can send data to the client without an explicit request.

A big advantage of comet is that each client always has a communication link open to the server side. The server side can push the event to the client by submitting (completes) the response as soon as the event arrives, or it can even accumulate and continuously send. Because the request remains open for a long time, the server side requires special functionality to handle all of these long lifetime requests. Figure 3 shows an example. (The 2nd section of this article series explains the server-side constraints in more detail).

Figure 3. Using Comet's reverse Ajax

Implementations of comet can be divided into two categories: those that use streams (streaming) and those that use long polling (length polling).

Comet using the HTTP stream

In flow (streaming) mode, there is a persistent connection that is opened. There will only be one long lifetime request (# in Figure 3), because each event that arrives on the server side is sent through the same connection. Therefore, the client needs to have a way to separate the different responses sent over the same connection. Technically, two common streaming technologies include the Forever IFrame (a hidden iframe), or the XMLHttpRequest (multi-part) attribute of an object that is used to create Ajax requests in JavaScript.

Forever Iframe

Forever iframe (persistent iframe) technology involves a hidden iframe tag placed on a page that points to the servlet path that returns the server-side event. Every time the event arrives, the servlet writes and refreshes a new script tag with JavaScript code inside it, and the content of the IFRAME is appended to the script tag, and the contents of the tag are executed.

1. Advantages: Simple to implement, available on all browsers that support IFRAME.

2. Disadvantages: There is no way to achieve reliable error handling or to track the status of the connection, because all connections and data are handled by the browser through the HTML tag, so you have no way of knowing when the connection has been disconnected at which end.

multi-part XMLHttpRequest

The second technique, more reliable, is the multi-part flag that is supported by some browsers (such as Firefox) on the XMLHttpRequest object. The AJAX request is sent to the server and remains open, and each time an event arrives, a partial response is written through the same connection, listing 6 shows an example.

Listing 6. Set the JavaScript code example for multi-part xmlhttprequest var xhr = $.ajaxsettings.xhr ();
Xhr.multipart = true;
Xhr.open (' Get ', ' Ajax ', true);
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4) {
Processevents ($.parsejson (Xhr.responsetext));
}
};
Xhr.send (NULL);

On the server side, things are slightly more complicated. First you have to set up a multiple-part request and then suspend the connection. Listing 7 shows how to suspend an HTTP stream request. (This series of 3rd chapters deals with these APIs in more detail.) )

Listing 7. Use the Servlet 3 API to suspend an HTTP stream request in the servlet protected void doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
Start the requested suspend
Asynccontext Asynccontext = Req.startasync ();
Asynccontext.settimeout (0);

To send a multiple-part separator to a client
Resp.setcontenttype ("multipart/x-mixed-replace;boundary=\")
+ Boundary + "" ");
Resp.setheader ("Connection", "keep-alive");
Resp.getoutputstream (). Print ("---" + boundary);
Resp.flushbuffer ();

Put the asynchronous context in the list for future use only
Asynccontexts.offer (Asynccontext);
}

Now, every time an event occurs, you can iterate through all the pending connections and write to them, as shown in Listing 8:

Listing 8. Use the Servlet 3 API to send event for (Asynccontext Asynccontext:asynccontexts) to a pending multi-part Request {
HttpServletResponse peer = (httpservletresponse)
Asynccontext.getresponse ();
Peer.getoutputstream (). println ("Content-type:application/json");
Peer.getoutputstream (). println ();
Peer.getoutputstream (). println (New Jsonarray ()
. Put (' at ' + New Date ()). ToString ());
Peer.getoutputstream (). println ("--" + boundary);
Peer.flushbuffer ();
}

The section in the Comet-straming folder for downloading files describes the HTTP stream, and when you run the example and open the home page, you'll see that as soon as the event arrives on the server side, it's not synchronized but they appear almost immediately on the page. Also, if you open the Firebug console, you can see that only one Ajax request is open. If you look further down, you will see that the JSON response is attached to the Response tab, as shown in Figure 4:

Figure 4. Firebug view of HTTP stream requests

As usual, the practice has some advantages and disadvantages:

1. Advantages: Only open a persistent connection, which is to save most of the bandwidth utilization of comet technology.

2. Disadvantages: Not all browsers support the multi-part flag. Some of the widely used libraries, such as the COMETD implemented in Java, are reported to have problems with Buffering. For example, some blocks of data (multiple parts) may be buffered and sent only if the connection is complete or the buffer is full, and this can lead to a higher latency than expected.

Comet using HTTP Long polling

Long polling (polling) mode involves the technology for opening the connection. The connection is kept open by the server side, and whenever an event occurs, the response is committed, and the connection is closed. Next. A new long polling connection is reopened by the client who is waiting for the new event to arrive.

You can use a script tag or a simple XMLHttpRequest object to implement HTTP long polling.

Script label

As with the IFRAME, the goal is to attach the script tag to the page for execution. The server side will: suspend the connection until an event occurs, then send the script contents back to the browser and reopen another script tag to get the next event.

1. Advantages: Because it is based on HTML tags, all of this technology is very easy to implement and can work across domains (by default, XMLHttpRequest does not allow requests to be sent to other domains or subdomains).

2. Disadvantages: Similar to the IFRAME technology, error handling is missing, you can not get the state of the connection or the ability to interfere with the connection.

XMLHttpRequest Long Polling

The second, and also a recommended implementation of comet, is to open an AJAX request to the server and wait for the response. The server side requires some specific functionality to allow the request to be suspended, and whenever an event occurs, the server side sends back the response in the pending request and closes the request, exactly as if you were shutting down the output stream of the servlet response. The client then uses this response and opens a new AJAX request to the server-side long lifetime, as shown in Listing 9:

Listing 9. Set JavaScript code example for long polling requests function long_polling () {
$.getjson (' Ajax ', function (events) {
Processevents (events);
Long_polling ();
});
}
Long_polling ();

At the back end, the code also uses the Servlet 3 API to suspend requests, just as the HTTP stream does, but you don't need all the parts of the code, and listing 10 gives an example.

Listing 10. Suspend a long polling Ajax request protected void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
Asynccontext Asynccontext = Req.startasync ();
Asynccontext.settimeout (0);
Asynccontexts.offer (Asynccontext);
}

When you receive an event, simply remove all pending requests and complete them, as shown in Listing 11:

Listing 11. Completes long polling AJAX requests while an event occurs (! Asynccontexts.isempty ()) {
Asynccontext Asynccontext = Asynccontexts.poll ();
HttpServletResponse peer = (httpservletresponse)
Asynccontext.getresponse ();
Peer.getwriter (). Write (
New Jsonarray (). Put (' at ' + New Date ()). ToString ());
Peer.setstatus (HTTPSERVLETRESPONSE.SC_OK);
Peer.setcontenttype ("Application/json");
Asynccontext.complete ();
}

In the accompanying download source file, the Comet-long-polling folder contains a long polling sample Web application that you can run using the MVN jetty:run command.

1. Advantages: The client can easily achieve good error handling system and time-out management. This reliable technology also allows a round-trip to the server-side connection, even if the connection is non-persistent (this is a good thing when your application has many clients). It can be used on all browsers, and you just have to make sure that the simple Ajax request sent to the XMLHttpRequest object is available.

2. Disadvantages: There are no important drawbacks compared to other technologies, like all the technologies we have discussed, the method still relies on stateless HTTP connections that require special functionality on the server side to temporarily suspend the connection.

Suggestions

Because all modern browsers support the Cross-domain resource sharing (Cross-origin Resource share,cors) specification, which allows XHR to perform cross-domain requests, scripting and IFRAME based technologies have become an outdated requirement.

The best way to implement and use comet as reverse Ajax is through the XMLHttpRequest object, which provides a true connection handle and error handling. Considering that not all browsers support the multi-part flag, and multiple shunts may experience buffering problems, it is recommended that you choose the comet mode of using the XMLHttpRequest object (a simple Ajax request that hangs on the server side) via an HTTP long poll. All AJAX-enabled browsers also support this approach.

Conclusion

This article provides an entry-level introduction to reverse Ajax technology, explores different ways to implement reverse Ajax communication, and illustrates the advantages and disadvantages of each implementation. Your specific situation and application needs will affect your choice of the most appropriate method. In general, however, if you want to have the best compromise in terms of low latency communication, timeout and error detection, simplicity, and good support for all browsers and platforms, choose to use the comet of the Ajax long polling request.

Read on to the 2nd part of this series: This section will explore the third reverse Ajax technology: WebSocket. Although not all browsers support the technology, WebSocket is certainly a very good reverse Ajax communication Medium, WebSocket eliminates all restrictions associated with the stateless nature of HTTP connections. The 2nd part also addresses the server-side constraints brought about by Comet and WebSocket Technologies.

Code download

Reverse_ajaxpt1_source.zip

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.