Servlet 3.0 Notes Asynchronous request Comet push IFRAME Demo

Source: Internet
Author: User

The SERVLET3 specification presents an asynchronous request, which is definitely a huge historical advance. The respective application server vendors have launched their own asynchronous request implementations (or comet, or server push support, or long connections), such as NIO Connection protocol support in Tomcat6, Jetty's continuations programming architecture, SUN, IBM, Bea, needless to say, the commercial version of the server to Comet support, naturally go in front of the open source application server, each king, there is no unified programming model, how a disorderly word. There are also a number of related comet frameworks, such as Pushlet, DWR, cometd, recently very hot HTML5 also lonely, launched WebSocket, just away from reality. Overall, in the Java world, very messy! Lack of specifications, without a unified programming model, can be heavily dependent on a particular server, or on a specific container. Fortunately, Servlet3 has an asynchronous request specification, and each application server vendor only needs to implement it on its own, so you can write an asynchronous servlet code that conforms to the specification without worrying about porting. Writing support for a comet-style servlet now is simple:
    1. Asyncsupported = True on the mark at the annotation;
    2. Final Asynccontext ac = Request.startasync ();
Here set the simple application environment: a very popular blog system, multi-person subscription, the end user just need to access the subscription page, when the background has a new blog post submission, the server will be actively pushed to the client, the new content automatically displayed on the user's screen. Throughout the process, users just need to open a page (that is, subscribe once), the background when there is new content will be actively displayed on the user browser, do not need to refresh anything. The following example uses an IFRAME, and the comet Stream will be expanded later. The theory will not be discussed in depth in this article, but will be discussed later. This system requires a post content feature: A new post-processing part of the code:
protected void DoPost (HttpServletRequest request,   HttpServletResponse response) throws Servletexception, IOException {  Micblog blog = new Micblog ();  Blog.setauthor ("Issuer");  Blog.setid (System.currenttimemillis ());  Blog.setcontent (Iso2utf8 (Request.getparameter ("content"));  Blog.setpubdate (New Date ());  Put it in the post queue to  NewBlogListener.BLOG_QUEUE.add (blog);  Request.setattribute ("message", "Post published successfully!");  Request.getrequestdispatcher ("/web-inf/pages/write.jsp"). Forward (    request, response);}  private static string Iso2utf8 (String str) {  try {   return new string (Str.getbytes ("iso-8859-1"), "UTF-8");  } catch (Unsupportedencodingexception e) {   e.printstacktrace ();  }  return null; }
When users need to subscribe to the interface of the blog update: the current page HTML code can explain some of the client's situation:
The DIV with the id "Showdiv" is here as a container for the organization to display the latest information. In the case of client logic, the details of how to interact with the server are shown in the Comet.js file:
/** * Client Comet JS Rendering section * @author [email protected] * @date 2010-10-18 * @version 1.0 */string.prototype.template=fun    Ction () {var args=arguments;    Return This.replace (/\{(\d+) \}/g, function (M, i) {return args[i]; });} var html = ' <div class= ' logdiv ' > ' + ' <div class= ' contentdiv ' >{0}</div> ' + ' <div class= ' Tipdiv ' > Last Date: {1}</div> ' + ' <div class= "clear" >&nbsp;</div> ' + ' </div> '; function showconte NT (JSON) {$ ("#showDiv"). Prepend (Html.template (json.content, Json.date));}  var server = ' Blogpush '; var comet = {Connection:false, iframediv:false, Initialize:function ()              {if (Navigator.appVersion.indexOf ("MSIE")! =-1) {comet.connection = new ActiveXObject ("Htmlfile");              Comet.connection.open ();              Comet.connection.write ("It is important to note that comet's handling of the object at initialization (initialize) and timeout (timeout) is perfect for IE and Firefox, and does not appear in the loading flag. Of course the Timeout method (timeout) is called on the server side to notify the client. There's always a progress bar underneath Chrome and opera, and there's no good solution for the moment. Background processing client request Request code:
/** * Responsible for Client Push * @author Yongboy * @date 2011-1-13 * @version 1.0 */@WebServlet (Urlpatterns = {"/blogpush"}, Asyncsupp Orted = true) public class Blogpushaction extends HttpServlet {private static final long Serialversionuid = 8546832356595L ; Private static final Log log = Logfactory.getlog (Blogpushaction.class); protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {R  Esponse.setheader ("Cache-control", "private");  Response.setheader ("Pragma", "No-cache");  Response.setcontenttype ("Text/html;charset=utf-8");  Response.setcharacterencoding ("UTF-8");  Final PrintWriter writer = Response.getwriter ();  Create a comet Iframe writer.println ("<!doctype HTML public \"-//W3C//DTD HTML 4.0 transitional//en\ ">");  Writer.println ("<script type=\" text/javascript\ ">var comet = window.parent.comet;</script>");  Writer.flush ();  Final Asynccontext ac = Request.startasync (); Ac.settimeout (10 * 60 * 1000);///10 minutes; TOMCAT7 The default is 10000 milliseconds Ac.addlistener (new Asynclistener () {public void OnComplete (AsyncEvent event) throws IOException {Lo    G.info ("the event:" + event.tostring () + "is all now!");   NewBlogListener.ASYNC_AJAX_QUEUE.remove (AC);  } public void OnTimeOut (AsyncEvent event) throws IOException {Log.info ("the event:" + event.tostring () + "is    Timeout now! ");    Attempting to send a time-out method call to the client, the client requests/blogpush again, and the Log.info ("try to notify the client the connection is a timeout now ...");    String alertstr = "<script type=\" text/javascript\ ">comet.timeout ();</script>";    Writer.println (ALERTSTR);    Writer.flush ();    Writer.close ();   NewBlogListener.ASYNC_AJAX_QUEUE.remove (AC); } public void OnError (AsyncEvent event) throws IOException {Log.info ("the event:" + event.tostring () + "is error    Now! ");   NewBlogListener.ASYNC_AJAX_QUEUE.remove (AC); } public void Onstartasync (AsyncEvent event) throws IOException {Log.info ("the event:" + event.toString () + "is Start Async now!");  }  }); NewBlogListener.ASYNC_AJAX_QUEUE.add (AC); }}
Each request requires Request.startasync (Request,response) to initiate asynchronous processing, get the Asynccontext object, set the timeout processing time (set for 10 minutes), and register an asynchronous listener. An asynchronous listener can be notified when an asynchronous request is initiated, completed, timed out, or an error occurs, and is an event delivery mechanism, which allows for better resource handling. In the long Connection timeout (ontimeout) event, the server proactively notifies the client to request registration again. If the intermediate client shuts down abnormally, the server-side push count reduces the invalid connection after the timeout. In a real application, you need to look for a better value to ensure that the server has a valid number of connections without wasting redundant connections. Each asynchronous request is stored in an efficient concurrent queue, processed uniformly in one thread, with specific logic code:
/** * Listener Individual thread push to client * @author Yongboy * @date 2011-1-13 * @version 1.0 */@WebListenerpublic class Newbloglistener Implem  Ents Servletcontextlistener {private static final log log = Logfactory.getlog (newbloglistener.class); public static final blockingqueue<micblog> blog_queue = new linkedblockingdeque<micblog> (); public static final queue<asynccontext> async_ajax_queue = new concurrentlinkedqueue<asynccontext> (); private static final String target_string = "<script type=\" text/javascript\ ">comet.showmsg (%s);</script>  "; Private String getformatcontent (Micblog blog) {return String.Format (target_string, buildjsonstring (blog));} public Voi D contextdestroyed (servletcontextevent arg0) {Log.info ("context is destroyed!"), public void contextinitialized (SERVL  Etcontextevent servletcontextevent) {Log.info ("context is initialized!"); Starts a thread-handling thread queue new Thread (runnable). Start ();   } private Runnable Runnable = new Runnable () {public void run () {Boolean isDone = true; while (IsDone) {if (!      Blog_queue.isempty ()) {try {log.info ("Async_ajax_queue size:" + async_ajax_queue.size ());      Micblog blog = Blog_queue.take ();      if (Async_ajax_queue.isempty ()) {continue;      } String Targetjson = getformatcontent (blog);  for (Asynccontext context:async_ajax_queue) {if (context = = null) {Log.info ("the current Async_ajax_queue        Is null now! ");       Continue       } log.info (Context.tostring ());       PrintWriter out = Context.getresponse (). Getwriter ();        if (out = = null) {Log.info ("The current Async_ajax_queue ' s printwriter is null!");       Continue       } out.println (Targetjson);      Out.flush ();      }} catch (Exception e) {e.printstacktrace ();     IsDone = false; }    }   }  } }; private static String buildjsonstring (Micblog blog) {map<string, object> info = new hashmap<string, object> (  ); Info.put ("Content", BloG.getcontent ());  Info.put ("Date", Dateformatutils.format (Blog.getpubdate (), "HH:mm:ss SSS"));  Jsonobject Jsonobject = jsonobject.fromobject (info); return jsonobject.tostring (); }}
Asynchronous request contextAsynccontextGets the output object (response), passing the JSON formatted sequence object to the client, how it is parsed, displayed, and determined by the client (see Comet.js). Given that the servlet is a single-instance multi-threaded, the best practice recommendation is not to start a separate thread in the servlet, this article is placed in the Servletcontextlistener listener so that when the Web site is started, a separate thread is created, and when there is a new post content, Traverse push all registered clients the entire process is combed:
    1. Client Request blog.html
    2. blog.html comet.js Start registering the Start event
    3. JS generates an IFRAME, requests/blogpush in an IFRAME, registers an asynchronous connection, sets a timeout of 10 minutes, registers an asynchronous listener
    4. The server receives the request, adding an asynchronous connection to the queue
    5. The client is waiting (long connection is established), waiting to be called
    6. Post a new blog post in the background
    7. Blog posts are put into the queue
    8. Been waiting for the standalone thread to process the blog post queue; format the blog post as a JSON object, one by one polling push to the client
    9. The client JS method is called, the JSON object is parsed, the HTML code is assembled and displayed on the current page.
    10. When the timeout occurs,/blogpush notifies the client that it has timed out, calls the timeout method, and removes from the asynchronous connection queue
    11. The client receives a notification, operates on the IFRAME, makes a connection request again, and repeats step 2
The approximate flowchart is as follows:
Its connection model, lazy, borrowed from IBM on a picture description:

Servlet 3.0 Notes Asynchronous request Comet push IFRAME Demo

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.