Ajax for Java developers: implementing Comet Web Applications using jetty and DWR

Source: Internet
Author: User
Tags implement sleep thread time interval ajax chat

As a widely used WEB application development technology, AJAX firmly established its position, followed by some of the common Ajax usage patterns. For example, Ajax is often used to respond to user input and then modify part of the page with new data obtained from the server. However, sometimes the Web application's user interface needs to be updated to respond to asynchronous events that occur on the server side without requiring user action-for example, displaying new messages to an Ajax chat application, or displaying changes from another user in a text editor. Because only the HTTP connection between the Web browser and the server can be established by the browser, the server cannot "push" the changes to the browser as the changes occur.

Ajax applications can solve this problem in two basic ways: One method is for browsers to poll the server for updates every few seconds, and the other way the server always opens a connection to the browser and sends it to the browser when the data is available. This article will show you how to use the Jetty servlet engine and DWR to implement a Comet WEB application with simplicity and efficiency.

Why use Comet?

The main disadvantage of polling methods is that when extended to more clients, a large amount of traffic is generated. Each client must regularly access the server to check for updates, which adds more load to the server's resources. The worst scenario is to use polling for applications that do not frequently update, such as an Ajax mail Inbox. In this case, a significant number of client polling is not necessary, and the server's answer to these polls will be "no new data generated." Although the server load can be mitigated by increasing the time interval for polling, this approach has the undesirable consequence of delaying client perceptions of server events. Of course, many applications can achieve some sort of trade-off to get an acceptable polling method.

Nevertheless, one of the advantages of attracting people to use the Comet strategy is its apparent efficiency. The client does not generate annoying traffic as it does with the polling method, and it can be published to the client immediately after the event occurs. However, maintaining a long connection on the open state also consumes server resources. The servlet will monopolize a thread when the waiting state's servlet holds a persistent request. This limits the scalability of Comet to the traditional servlet engine because the number of clients quickly exceeds the number of threads that the server stack can effectively handle.

What's the difference between Jetty 6?

The purpose of Jetty 6 is to extend a large number of simultaneous connections, using the Java™-language non-blocking I/O (Java.nio) library and using an optimized output buffer architecture (see Resources). Jetty also provides some tips for dealing with long-term connections: This feature is called continuations. I will use a simple servlet to demonstrate the continuations, which will accept the request, wait for processing, and then send a response. Next, I'll show you what happens when the number of clients exceeds the processing thread provided by the server. Finally, I'll use continuations to implement the servlet again, and you'll understand the role continuations plays.

To facilitate understanding of the following example, I will limit the Jetty servlet engine to a single request processing thread. Listing 1 shows the related configuration in Jetty.xml. I actually need to use three threads in the ThreadPool: the Jetty server itself uses one thread, the other runs the HTTP connector, and detects the request. The third thread executes the servlet code.

Listing 1. Jetty configuration for a single servlet thread<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN"
 "http://jetty.mortbay.org/configure.dtd">
<Configure id="Server" class="org.mortbay.jetty.Server">
  <Set name="ThreadPool">
   <New class="org.mortbay.thread.BoundedThreadPool">
    <Set name="minThreads">3</Set>
    <Set name="lowThreads">0</Set>
    <Set name="maxThreads">3</Set>
   </New>
  </Set>
</Configure>

Next, in order to simulate the wait for an asynchronous event, listing 2 shows the Blockingservlet service () method that uses Thread.Sleep () to pause 2000 milliseconds before the thread ends. It also outputs the system time at the start and end of execution. In order to distinguish between output and different requests, the request parameters that are identifiers are also recorded in the log.

Listing 2. Blockingservlet

public class Blockingservlet extends HttpServlet {
public void Service (HttpServletRequest req, httpservletresponse Res)
Throws Java.io.IOException {
String reqid = req.getparameter ("id");
Res.setcontenttype ("Text/plain");
Res.getwriter (). println ("Request:" +reqid+ "\tstart:\t" + New Date ());
Res.getwriter (). Flush ();
try {
Thread.Sleep (2000);
catch (Exception e) {}
Res.getwriter (). println ("Request:" +reqid+ "\tend:\t" + New Date ());
}
}

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.