What is reverse ajax?
Reverse Ajax is essentially a concept: being able to senddata from the server to the client. In a standard HTTP Ajax request, data issent to the server. Reverse Ajax can be simulated to issue an Ajax request, inspecific ways that are covered in this article, so the server can send eventsto the client as quickly as possible (low-latency communication).
反转AJAX实质上是一种概念:能够从服务器发送到客户端的数据。在一个标准的HTTPAjax请求,数据发送到服务器。反转AJAX可以模拟发出一个Ajax请求,在这篇文章中所涵盖的具体方式,使服务器可以发送事件给客户端尽快(低延迟通讯)。
方式一:Polling
Polling involves issuing a requestfrom the client to the server to ask for some data. This is obviously a mereAjax HTTP request. To get the server events as soon as possible, the pollinginterval (time between requests) must be as low as possible.
There's a drawback: if this interval is reduced, the clientbrowser is going to issue many more requests, many of which won't return anyuseful data, and will consume bandwidth and processing resources for nothing.
轮询涉及发出要求一些数据的服务器的客户端的请求。这显然是一个单纯的Ajax HTTP请求。为了尽快得到服务器的事件,轮询间隔(请求之间的时间)必须尽可能低。
有一个缺点:如果这个间隔缩小,客户端浏览器会发出更多的请求,其中许多将不会返回任何有用的数据,将白白消耗的带宽和处理资源。
HTTP polling
JSONP polling
JSONP polling is essentially the same as HTTP polling. Thedifference, however, is that with JSONP you can issue cross-domain requests(requests not in your domain). A JSONP request can usually be recognized by itscallback parameter and returned content, which is executable JavaScript code
CodeDemo:
Client:
Server:
Polling in JavaScript hasadvantages and disadvantages.
- Advantages: It's really easy to implement and does not require any special features on the server side. It also works in all browsers.
- Disadvantage: This method is rarely employed because it does not scale at all. Imagine the quantity of lost bandwidth and resources in the case of 100 clients each issuing polling requests for 2 seconds, where 30% of the requests returned no data.
方式二:Piggyback
Piggyback polling is a much more clever method than pollingsince it tends to remove all non-needed requests (those returning no data).There is no interval; requests are sent when the client needs to send a requestto the server. The difference lies in the response, which is split into twoparts: the response for the requested data and the server events, if any occurred.Figure 2 shows an example.
When implementing the piggyback technique, typically all Ajaxrequests targeting the server might return a mixed response
- Advantages: With no requests returning no data, since the client controls when it sends requests, you have less resource consumption. It also works in all browsers and does not require special features on the server side.
- Disadvantage: You have no clue when the events accumulated on the server side will be delivered to the client because it requires a client action to request them.
Code Demo
Client:
Server:
方式三:Comet
Reverse Ajax with polling or piggyback is very limited: itdoes not scale and does not provide low-latency communication (when eventsarrive in the browser as soon as they arrive on the server). Comet is a web application model where a request is sent to theserver and kept alive for a long time, until a time-out or a server eventoccurs. When the request is completed, another long-lived Ajax request is sentto wait for other server events. With Comet, web servers can send the data tothe client without having to explicitly request it.
The big advantage of Comet is that each client always has acommunication link open to the server. The server can push events on the clientsby immediately committing (completing) the responses when they arrive, or itcan even accumulate and send bursts. Because a request is kept open for a longtime, special features are required on the server side to handle all of theselong-lived requests.
Implementations of Comet can be separated into two types:those using streaming mode, and those using long polling.
Comet using HTTP streaming
Instreaming mode, one persistent connection is opened. There will only be along-lived request (#1 in Figure 3) since each eventarriving on the server side is sent through the same connection. Thus, itrequires on the client side a way to separate the different responses comingthrough the same connection. Technically speaking, two common techniques forstreaming include Forever Iframes (hidden IFrames) or the multi-part feature ofthe XMLHttpRequest object used to createAjax requests in JavaScript.
ForeverIframes
TheForever Iframes technique involves a hidden Iframe tag put in the page with its src attribute pointing to theservlet path returning server events. Each time an event is received, theservlet writes and flushes a new script tag with the JavaScript code inside.The iframe content will be appended with this script tag that will getexecuted.
- Advantages: Simple to implement, and it works in all browsers supporting iframes.
- Disadvantages: There is no way to implement reliable error handling or to track the state of the connection, because all connection and data are handled by the browser through HTML tags. You then don't know when the connection is broken on either side.
Multi-part XMLHttpRequest
Thesecond technique, which is more reliable, is to use the multi-part flagsupported by some browsers (such as Firefox) on theXMLHttpRequest object. An Ajax requestis sent and kept open on the server side. Each time an event comes, amulti-part response is written through the same connection. Listing 6 shows anexample.
- Advantage: Only one persistent connection is opened. This is the Comet technique that saves the most bandwidth usage.
- Disadvantage: The multi-part flag is not supported by all browsers. Some widely used libraries, such as CometD in Java, reported issues in buffering. For example, chunks of data (multi-parts) may be buffered and sent only when the connection is completed or the buffer is full, which can create higher latency than expected.
Code Demo
Client:
Server:
Comet using HTTP long polling
The long polling mode involves techniques that open aconnection. The connection is kept open by the server, and, as soon as an eventoccurs, the response is committed and the connection is closed. Then, a newlong-polling connection is reopened immediately by the client waiting for newevents to arrive.
长轮询模式涉及的技术,打开一个连接。连接是由服务器保持开放,并,只要事件发生时,响应承诺和关闭连接。然后,一个新的长轮询连接立即重新打开,等待新的事件到达客户端。
You can implement HTTP longpolling by using script tags or a mere XMLHttpRequest
object.
Script tags
As with iframes,the goal is to append a script tag in your page to get the script executed. Theserver will: suspend the connection until an event occurs, send the scriptcontent back to the browser, and then reopen another script tag to get the nextevents.
- Advantages: Because it's based on HTML tags, this technique is very easy to implement and works across domains (by default,
XMLHttpRequest
does not allow requests on other domains or sub-domains). - Disadvantages: Similar to the iframe technique, error handling is missing, and you can't have a state or the ability to interrupt a connection.
XMLHttpRequest long polling
Thesecond, and recommended, method to implement Comet is to open an Ajax requestto the server and wait for the response. The server requires specific featureson the server side to allow the request to be suspended. As soon as an eventoccurs, the server sends back the response in the suspended request and closesit, exactly like you close the output stream of a servlet response. The clientthen consumes the response and opens a new long-lived Ajax request to the serve。
- Advantages: It's easy to implement on the client side with a good error-handling system and timeout management.This reliable technique also allows a round-trip between connections on the server side, since connections are not persistent (a good thing, when you have a lot of clients on your application)支持后端服务器间的交互?. It also works on all browsers; you only make use of the XMLHttpRequest object by issuing a simple Ajax request.
- Disadvantage: There is no main disadvantage compared to other techniques. But, like all techniques we've discussed, this one still relies on a stateless HTTP connection, which requires special features on the server side to be able to temporarily suspend it.
Code Demo
Client:
Server:
方式四: WebSockets
What is the WebSockets?
WebSockets, which emerged in HTML5, is a much more recent Reverse Ajaxtechnique than Comet. WebSockets enables bi-directional, full-duplexcommunication channels, and many browsers (Firefox, Google Chrome, and Safari)already support it. The connection is opened through an HTTP request, called aWebSockets handshake, with some special headers. The connection is kept alive,and you can write and receive data in JavaScript as if you were using a raw TCPsocket.
A WebSocket URL is started by typing ws://
or wss://
(on SSL).
WebSockets is a very powerful Reverse Ajax solution, despite a fewdrawbacks. It's not currently implemented on all browsers, and isn't easy to useon the server side in Java without the help of a Reverse Ajax library. Becauseyou aren't using a standard request-response style, you cannot rely on thefilter chain execution for scopes. Comet and WebSockets requireserver-side-specific features of the containers, so you need to pay attentionwhen using a recent container or it will not scale.
WebSockets 不被所有的浏览器支持,虽然文中提到FireFox、Chrome等浏览器支持,但是我个人本地部署demo服务后,这两种浏览器仍然不支持(据查资料有些反馈为该技术尚存在安全问题,不成熟);
另一个值得注意的是,WebSockets技术并没有形成业界标准(JAVA标准),目前仅限于个别组织研究深入中,如 Jetty、 Glassfish等,伴随着这个问题,目前也只有jetty Glassfish容器支持该技术。使用起来受限因素很多.
容器支持对比
Recommendations
Becauseall modern browsers support the Cross-Origin Resource Sharing (CORS)specification, which allows XHR to perform cross-domain requests, the need forscript-based and iframe-based techniques becomes deprecated.
The bestway to implement and use Comet for Reverse Ajax is through the XMLHttpRequest
object, which provides a real connection handle and errorhandling. Considering that not all browsers support the multi-part flag, andmulti-part streaming can be subject to buffering issues, it is recommended thatyou use Comet through HTTP long polling with the XMLHttpRequest
object (a simple Ajax request that is suspended on the serverside). All browsers supporting Ajax also support this method.
因为所有的现代浏览器支持跨域资源共享(CORS)规范,它允许的XHR执行跨域请求,基于脚本和基于IFRAME的技术成为过时的需要。
实施和使用反转AJAX彗星的最佳方式是通过XMLHttpRequest对象,它提供了一个真正的连接处理和错误处理。
考虑到并不是所有的浏览器支持多部分的标志,和多部分流缓冲问题,建议您使用通过HTTP长轮询彗星与XMLHttpRequest对象(一个简单的Ajax请求在服务器上暂停侧)。所有支持Ajax的浏览器也支持此方法。
Conclusion
This article provided anintroduction to Reverse Ajax techniques. It explored different ways toimplement Reverse Ajax communication, and it explained the advantages anddrawbacks for each implementation. Your particular situation and therequirements of your application will influence which method is best for you.
Generally speaking though, Comet with Ajaxlong-polling requests is the way to go if you want the best compromise of: low-latencycommunication; timeout and error detection; simplicity; and good support fromall browsers and platforms
一般来说,Comet with Ajax long-pollin是一种好的折衷方式来满足:
低延迟通信超时和错误检测;
简单;
所有浏览器和平台的良好支持;
常用容器的支持。
原文引自:
http://www.ibm.com/developerworks/web/library/wa-reverseajax1/
http://www.ibm.com/developerworks/web/library/wa-reverseajax2/
http://www.ibm.com/developerworks/web/library/wa-reverseajax3/
http://www.ibm.com/developerworks/web/library/wa-reverseajax4/
http://www.ibm.com/developerworks/web/library/wa-reverseajax5/