Web Live chat Comet push Technology

Source: Internet
Author: User
Tags live chat

Transferred from: http://www.cnblogs.com/wodemeng/archive/2012/04/06/2435302.html

This evening friends encounter Web services side push technology problem, I looked up the next information, learning the next

Source code: Http://files.cnblogs.com/wodemeng/AspNetComet.zip

Comet is sometimes also called reverse Ajax or server-side push technology (server-side push). The idea is simple: push data directly from the server to the browser without waiting for the browser to request data.

============= General Description =======================

The advent of Ajax has made Comet possible. The one-way nature of HTTP can be effectively circumvented. There are actually a few different ways to get around this. As you might have guessed, the easiest way to support Comet is polling (poll). Use a XMLHttpRequest call to the server, return, wait for a fixed amount of time (usually using JavaScript setTimeout functions), and then call again. This is a very common technique. For example, most webmail applications use this technique to display e-mail messages when e-mail arrives.

There are pros and cons to this technology. In this case, you expect a quick return response, just like any other Ajax request. There must be a pause between requests. Otherwise, successive requests can burst the server, and in this case it is obviously not scalable. This pause causes the application to generate a delay. The longer the pause, the more time it takes for new data on the server to reach the client. If you shorten the pause time, you will again face the risk of the server being overwhelmed. But on the other hand, this is obviously the simplest way to implement Comet.

It should now be pointed out that many people think polling is not a Comet. Instead, they argue that Comet is a solution to the limitations of polling. The most common "true" Comet technique is a variant of polling, long polling. The main difference between polling and long polling is how long it takes the server to respond. Long polling usually keeps the connection for a long time-usually a few seconds, but it can be a minute or even longer. When an event occurs on the server, the response is sent and then closed, and polling starts again immediately.

The advantage of long polling over general polling is that once the data is available, it is immediately sent from the server to the client. The request may wait for a longer period without any data being returned, but once the new data is available, it is immediately sent to the client. So there is no delay. If you have used a WEB-based chat program, or any program that claims to be "in real time," it is likely that this technique is used.

Long polling has a variant, which is the third style of Comet. This is often referred to as a stream (streaming). In this style, the server pushes the data back to the client, but does not close the connection. The connection remains open until it expires and causes the request to be re-issued. XMLHttpRequestThe specification shows that you can check readyState whether the value is 3 or receiving (instead of 4 or Loaded) and get the data that is being "out" from the server. As with long polling, there is no delay in this way. When the data on the server is ready, the data is sent to the client. Another advantage of this approach is that it can significantly reduce the requests sent to the server, thus avoiding the overhead and latency associated with setting up the server connection. Unfortunately, there are XMLHttpRequest many different implementations in different browsers. This technology can only be reliably used in newer versions of Mozilla Firefox. For Internet Explorer or Safari, you still need to use long polling.

At this point, you might think that there is a big problem with long polling and streaming. The request needs to exist on the server for a longer period of time. This breaks the model of using one thread per request, because the thread used for a request has not been freed. Even worse, the thread is idle until the data is sent back. This is obviously not scalable. Fortunately, modern WEB servers have many ways to solve this problem.

============= introduction of various knowledge points =======================

We want to understand reverse Ajax, polling (polling), streaming (streaming), comet, and long polling (long polling), learn how to implement different reverse Ajax communication technologies, and explore the pros and cons of each approach.

  Ajax, reverse Ajax, and WebSocket

Asynchronous JavaScript and XML (asynchronous JavaScript and Xml,ajax), a browser feature that can be accessed via JavaScript, It allows the script to send an HTTP request to the behind-the-scenes web site without reloading the page. Ajax has been around for more than a decade, and although its name contains XML, you can almost send 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 the name of a place by its zip code.

Listing 1. Ajax Request Examples

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 source code that is available for download 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 be used in some specific way to simulate an AJAX request, which is discussed in this article, so that the server can send events (low latency traffic) to the client as quickly as possible.

WebSocket technology comes from HTML5, a recently emerging technology that many browsers already support (Firefox, Google Chrome, Safari, and so on). WebSocket enables bidirectional, full-duplex communication channels, which open the connection through some kind of HTTP request called the WebSocket handshake, and use some special headers. 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 will talk about it in the second part of this article series.

  Reverse Ajax Technology

The purpose of reverse Ajax is to allow server-side push of information to clients. The AJAX request is stateless by default and can only be requested from the client to the server side. You can bypass this limitation by using technology to simulate reactive communication between the server side and the client.

  HTTP Polling and Jsonp polling

Polling (polling) involves making a request from the client to the server to get some data, which is obviously a purely Ajax HTTP request. In order to get server-side events as quickly as possible, the polling interval (the time between two requests) must be as small as possible. But there is one drawback: if the interval is reduced, the client browser makes more requests, and many of these requests do not return any useful data, which in vain wastes 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 received.

Figure 1. Reverse Ajax using HTTP polling

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

To implement polling in JavaScript, you can use SetInterval to make periodic 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 gives the bandwidth that the polling method consumes, with a small interval, but you can see that some requests do not return events, and listing 3 shows the output of this poll example.

Listing 3. The output of the polling demo example

[Client] checking for events ...
[Client] No event
[Client] checking for events ...
[Client]2 Events
[Event] At Sun June 0515:17:14 EDT 2011
[Event] At Sun June 0515:17:14 EDT 2011
[Client] checking for events ...
[Client]1 Events
[Event] At Sun June 0515:17:16 EDT 2011

Advantages and disadvantages of polling implemented with JavaScript:

1. Advantages: It is easy to implement, does not require any server-side specific features, and can work on all browsers.

2. Cons: This method is rarely used because it is completely non-scalable. Imagine the loss of bandwidth and the amount of resources in cases where 100 clients each issued a 2-second polling request, in which case 30% of the requests did not return data.

  Piggyback

A piggyback poll (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 requests to the server when needed. The difference is that in 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, as shown in Listing 4 below for an example of an implementation in the download of the article.

Listing 4. Piggyback code example

$ (' #submit '). Click (function () {
$.post (' Ajax ', function (data) {
var valid = Data.formvalid;
Working with validation results
The other part of the response (event) is then processed
Processevents (data.events);
});
});

Listing 5 shows some of the piggyback output.

Listing 5. Piggyback output Example

[Client] checking for events ...
[Server] form valid? True
[Client]4 Events
[Event] At Sun June 0516:08:32 EDT 2011
[Event] At Sun June 0516:08:34 EDT 2011
[Event] At Sun June 0516:08:34 EDT 2011
[Event] At Sun June 0516:08:37 EDT 2011

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

1. Pros: There is no request to return data because the client controls when the request is sent and consumes less resources. This method is also available on all browsers and does not require special features on the server side.

2. Cons: When events that accumulate on the server side need to be routed to the client, you do not know at all, because this requires a client behavior to request them.

  Comet

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

One of the great advantages of comet is that each client always has a communication link open to the server side. The server side can push events to the client by committing (completing) the response as soon as the event arrives, or it can even accumulate and then continue sending. Because requests remain open for long periods of time, the server side needs special features to handle all these long-lived requests. Figure 3 shows an example. (the 2nd chapter of this article series explains server-side constraints in more detail).

Figure 3. Using Comet's reverse Ajax

The implementation of comet can be divided into two categories: those that use the stream (streaming) and those that use long polling (longer polling).

  Comet using the HTTP stream

In the flow (streaming) mode, a persistent connection is opened. There will only be one long lifetime request (# 3 in Figure #), 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 techniques include the Forever IFrame (hidden iframe), or the multipart (multi-part) feature of the XMLHttpRequest object that is used to create Ajax requests in JavaScript.

  Forever Iframe

The Forever iframe (persistent iframe) technique involves a hidden iframe tag placed on a page that has the SRC attribute pointing to the servlet path that returns the server-side event. Each time the event arrives, the servlet writes and refreshes a new script tag with JavaScript code inside it, and the contents of the IFRAME are appended to the script tag, and the contents of the tag are executed.

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

2. Cons: There is no way to implement reliable error handling or to track the status of a connection, because all the connections and data are handled by the browser through HTML tags, so you have no way of knowing when the connection is broken at which end.

  multi-part XMLHttpRequest

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

Listing 6. Sample JavaScript code to set 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 multipart request and then suspend the connection. Listing 7 shows how to suspend an HTTP stream request. (This series of 3rd chapters talk about these APIs in more detail.) )

Listing 7. Use the Servlet 3 API to suspend an HTTP stream request in a servlet

protected void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
Start pending on request
Asynccontext Asynccontext = Req.startasync ();
Asynccontext.settimeout (0);

To send back a multipart delimiter to the client
Resp.setcontenttype ("Multipart/x-mixed-replace;boundary=\" "
+ boundary + "\" ");
Resp.setheader ("Connection", "keep-alive");
Resp.getoutputstream (). Print ("--" + boundary);
Resp.flushbuffer ();

Put the async context in the list to be used in the future
Asynccontexts.offer (Asynccontext);
}

Now, each time an event occurs, you can traverse all the pending connections and write data to them, as shown in Listing 8:

Listing 8. Using the Servlet 3 API to send events to a multipart request that is pending

for (Asynccontext asynccontext:asynccontexts) {
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 sections in the Comet-straming folder of the downloadable files in this article describe the HTTP stream, and when you run the example and open the home page, you will see that as soon as the event arrives on the server side, it will appear on the page almost immediately, although it is not synchronized. And, 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, which is shown in 4:

Figure 4. Firebug view of HTTP stream requests

As a usual practice, there are some advantages and disadvantages:

1. Pros: Only one persistent connection is turned on, which is the comet technology that saves most of the bandwidth utilization.

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

  Using HTTP long polling for comet

The long polling mode involves the technique of opening a 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 waiting for the new event to arrive.

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

  Script tag

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

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

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

  XMLHttpRequest Long Polling

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

Listing 9. Sample JavaScript code to set up long polling requests

function long_polling () {
$.getjson (' Ajax ', function (events) {
Processevents (events);
Long_polling ();
});
}
Long_polling ();

In the backend, the code also uses the Servlet 3 API to suspend the request, just as the HTTP stream does, but you don't need all the multipart processing code, listing 10 gives an example.

Listing 10. Suspends 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 an event is received, simply remove all pending requests and complete them, as shown in Listing 11:

Listing 11. Complete long polling of Ajax requests when an event occurs

while (!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 app that you can run with the MVN jetty:run command.

1. Advantages: The client can easily implement a good error handling system and timeout management. This reliable technology also allows a roundtrip between connections to the server side, even if the connection is non-persistent (a good thing when your app has a lot of clients). It can be used on all browsers; you just need to make sure that the simple Ajax request that the XMLHttpRequest object is using is sent to you.

2. Cons: Compared to other technologies, there is no significant disadvantage, like all of the technologies we have discussed, the method still relies on stateless HTTP connection, which requires the server side has special features to temporarily suspend the connection.

  Suggestions

Because all modern browsers support cross-domain resource sharing (cross-origin Resource share,cors) specifications that allow XHR to perform cross-domain requests, script-based and IFRAME-based technologies have become obsolete.

The best way to implement and use comet as a 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 that multiple shunts may experience buffering problems, it is recommended that you choose a comet pattern that uses the XMLHttpRequest object (a simple Ajax request that hangs on the server side) via the HTTP long polling All AJAX-enabled browsers also support this approach.

  Conclusion

This article provides an entry-level introduction to reverse Ajax technology, the article explores the different ways to implement reverse Ajax communication, and explains 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 between low-latency communication, timeouts and error detection, simplicity, and good support for all browsers and platforms, then choose to use the Ajax long polling request comet.

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

Turn from:

http://kb.cnblogs.com/page/112185/

http://www.ibm.com/developerworks/cn/web/wa-cometjava/

Web Live chat Comet push Technology

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.