Developing Web Applications using Comet and Ajax by wrn10268

VIEWS: 0 PAGES: 58

									Developing Revolutionary Web
Applications using Comet and Ajax
Tao Michael Li
Technology Evangelist

                                    1
Agenda
• Web 2.0
• Introduction to Comet
• Asynchronous HTTP and the Server
• Develop a Two Player Game using Comet
  (demo)
• Develop a Slideshow Chat Application using
  Cometd (demo)
• Summary and Resources




                                               2
Web 2.0
A Web by the people, for the people.
Documents on the web increasingly generated by
users




Out of the Information Age, into the Participation Age




                                                     3
The Asynchronous Web Revolution
The Web enters the Participation Age.
• Ajax is still typically synchronous with user
  events
• Full asynchrony has updates pushed from server
  any time
  > Update pages after they load
  > Send users notifications
• Allow users to communicate and collaborate
  within the web application
• Called “Ajax Push”, “Comet”, or “Reverse Ajax”
  > This is the full realization of Ajax, now fully
    asynchronous
                                                      4
Server-mediated Collaboration




                                         External Application



                       Server



    User
               • User Initiated
   Push                                    Push
   Action      • Application Initiated

    Client 1                              Client 2




                                                                5
Applications in the Participation Age
Application-mediated communication.
 Distance learning
 Collaborative authoring
 Auctions
 Shared WebDAV filesystem
 Blogging and reader comments
 SIP-coordinated mobile applications
 Hybrid chat/email/discussion forums
 Customer assistance on sales/support pages
 Multi-step business process made collaborative
 Shared trip planner or restaurant selector with maps
 Shared calendar, “to do” list, project plan
 Games

                                                        6
Agenda
• Web 2.0
• Introduction to Comet
• Asynchronous HTTP and the Server
• Develop a Two Player Game using Comet
  (demo)
• Develop a Slideshow Chat Application using
  Cometd (demo)
• Summary and Resources




                                               7
What is Comet (Ajax Push)?
Responsive, low-latency interaction for the web
• A programming technique that enables web
  servers to send data to the client without having
  any need for the client to request for it
• Allows creation of highly responsive, event-
  driven web applications
  > Keep clients up-to-date with data arriving or changing
    on the server, without frequent polling
• Pros
  > Lower latency, not dependent on polling frequency
  > Server and network do not have to deal with frequent
    polling requests to check for updates

                                                             8
Ajax Poll vs Ajax Push
Bending the rules of HTTP.




• Comet Refers to both the Long Polling and Streaming
  methods of web programming
                                                        9
Ajax Poll vs Ajax Push
Bending the rules of HTTP.
• Poll:
  > Send a request to the server every X seconds
  > The response is “empty” if there is no update
• Long Poll: (most popular, demo use)
  > Send a request to the server, wait for an event to
    happen, then send the response
  > The response is never empty
  > HTTP specification satisfied: indistinguishable from
    “slow” server
• Http Streaming:
  > Send a request, wait for events, stream multi-
    part/chunked response, and then wait for the events
  > The response is continually appended to
                                                           10
Comet Examples
• GMail and GTalk
• Meebo
• 4homemedia.com
  (using GlassFish project's Comet)
• JotLive
• KnowNow
• Many more …




                                      11
Agenda
• Web 2.0
• Introduction to Comet
• Asynchronous HTTP and the Server
• Develop a Two Player Game using Comet
  (demo)
• Develop a Slideshow Chat Application using
  Cometd (demo)
• Summary and Resources




                                               12
How Push works
Keep an open connection.
• Deliver data over a previously opened
  connection
• Always “keep a connection open”
  > do not respond to the initiating request until event
    occurs
• Streaming is an option
  > send response in multiple parts without closing the
    connection in between




                                                           13
Server Architecture Challenge
Can Push scale?
• Using blocking, synchronous technology will
 result in a blocked thread for each open
 connection that is “waiting”
  > Every blocked thread will consume memory
  > This lowers scalability and can affect performance
• To get the Java Virtual Machine (JVM™) to scale
   to 10,000 threads and up needs specific tuning
  and is not an efficient way of solving this
• Servlets 2.5 are an example of blocking,
  synchronous technology

                                                         14
Architecture Challenges
The serious effect of blocking threads.




                                          (default thread stack
                                          size)




                                                                  15
Technology Solution
NIO avoids blocked threads.
 • Use new I/O (NIO) non-blocking sockets to
   avoid blocking a thread per connection
 • Use technology that supports asynchronous
   request processing
   > Release the original request thread while waiting for
     an event
   > May process the event/response on another thread
     than the original request
 • Advantages
   > Number of clients is primarily limited by the number
     of open sockets a platform can support
   > Could have all clients (e.g. 10’000) “waiting” without
     any threads processing or blocked
                                                              16
Server-side Ajax Push: Required functionality
A spectrum of asynchronicity.

 Asynchronous IO
 • Asynchronous read and write
 Suspendable Requests/Response
 • Suspend/resume
 Support Delivery Guarantee mechanism
 • Push data from one connection to another
 • Ability to aggregate/filter/transform data before
   the push operation

                                                       17
Server-side Ajax Push: Who supports what
The asynchronicity matrix.



Container   Asynchronous IO   Suspendible    Delivery
                               Request/     Guarantee
                               Response


Jetty                             X
Tomcat            X               X
GlassFish         X               X            X
Resin                             X
WebLogic                          X


                                                        18
Introduction to GlassFish Grizzly Comet
• Glassfish uses Grizzly Comet to realize AJAX
  push
• Grizzly Comet is a framework that ship with
  GlassFish v1|2|3, and can also be embedded
  into any application using the Grizzly Embedded
  interface (no GlassFish involved)
• The Grizzly Comet Framework includes a set of
  components that can be used for building Comet
  based application:
  > Grizzly Comet Framework, Continuation, Grizzlet,
    Messages Bus, Bayeux support


                                                       19
Grizzly Comet Components



     Grizzlet   Bayeux      Continuation   Messages Bus


                Grizzly Comet Framework


                     Grizzly HTTP


                 Grizzly NIO Framework




                                                          20
Asynchronous Ajax Demo
Grizzlet with Project jMaki on GlassFish




                                           21
Agenda
• Web 2.0
• Introduction to Comet
• Asynchronous HTTP and the Server
• Develop a Two Player Game using Comet
  (demo)
• Develop a Slideshow Chat Application using
  Cometd (demo)
• Summary and Resources




                                               22
How it works - setup


  client     Long lived connections

                              handler
                                          Shareable Comet
  client                    handler       Context

                                handler


  client



                                                            23
How it works: Interactions


  client     Client push

                              handler

  client                    handler       Shareable Comet
           Server push                    Context
                                handler

  client      Server push



                                                            24
Grizzly Comet Framework
• The Framework contains the classes required to
  add support for Comet in a Web Application
• Main classes to interact with (details next):
  > CometEngine
  > CometContext
  > CometHandler
  > NotificationHandler
  > CometReader
  > CometWriter




                                                   25
Grizzly Comet Framework
• CometContext
  > A shareable “space” to which applications may
    subscribe and from which the multiple subscribers
    (CometHandler) receive updates
• CometHandler
  > A CometHandler contains the business logic of what
    will be pushed back to the browser
  > A CometHandler might be invoked by the Container:
     ● When a push operation happens
     ● When a I/O operations are ready to be process
       (asynchronous read or write)
     ● When the browser close the connection



                                                         26
Grizzly Comet Framework (cont.)
• NotificationHandler
  > An inside object that you will decide to what to do with
    the push operation:
     ● Throttle: if too many push occurs simultaneously,
       should we delay them?
     ● Aggregate: should we cache push operations and
       aggregate them to avoid overloading the network?
     ● Filter: should all messages by pushed back to the
       client?
     ● Should a thread pool be used to improve the push
       operation? Should a JMS backed be used to deliver
       the message?
  > The DefaultNotificationHandler push all messages



                                                               27
 Software and Configuration

• Glassfish Application Server (V2 or V3 TP2)
  > Needs to be enabled for Comet
     ● Configure using GlassFish V2 admin console
     ● Configure in NetBeans 6.1+ for GlassFish V3
     ● or Command line
          – asadmin set server.http-service.http-listener.http-listener-
            1.property.cometSupport=true
     ● or Edit domain.xml in GlasFish
          – <http-listener id="http-listener-1" port="8080"><property
            name="CometSupport" value="true" />
• Grizzly Comet APIs
• A browser Client, running Javascript, support Ajax

                                                                           28
GlassFish V3 Comet Enable (in NetBeans)




                                          29
Enable Comet in GlassFish V2 Admin
Console




                                     30
Four Simple Steps for Comet
• Step 1: Initialize Comet
• Step 2: Define your CometHandler
• Step 3: Add CometHandler to CometContext
• Step 4: Advertise changes
• Step 5: Clients handle the changes respectively




                                                    31
Step 1: Initialize Comet
 //In TTTCometServlet class...
 public void init(ServletConfig config) {
       ServletContext context =
     config.getServletContext();
          contextPath = context.getContextPath() +
"/TTTComet1";
          CometEngine engine = CometEngine.getEngine();
          CometContext cometContext =
                          engine.register(contextPath);
          cometContext.setExpirationDelay(120 * 1000);
//All connections registered to a CometContext automatically
   becomes suspended, waiting for an event (a push) to happen
//A browser receives only those messages after the client “register “
   to a CometContext
//CometContex contains references to all suspended connections
   (encapsulated inside a CometHandler)
                                                                        32
 Step 2: Define a CometHandler
• The CometHandler<E> interface has these methods
 //Invoked when CometContext.notify() is called
 public void onEvent(CometEvent ce);
 // Invoked when the browser close a suspended
 // connection or when the suspend timeout expire
 public void onInterrupt(CometEvent ce);
 // Invoked when the request is suspended
 public void onInitialize(CometEvent ce);
 // Attach an object
 // most probably the HttpServletResponse
 public void attach(E e);

• Long Polling, in onEvent(event)

                                                    33
  CometHandler: TTTHandler
//Inside the TTTComet Servlet class...
private class TTTHandler implements
CometHandler<HttpServletResponse> {
  private HttpServletResponse response;
//When a push operation happens, onEvent invoked after
CometContext.notify() is called
  public void onEvent(CometEvent event) throws IOException {
       if (CometEvent.NOTIFY == event.getType()) {
             PrintWriter writer = response.getWriter();
             writer.write(
             "<script type='text/javascript'>parent.chImg("
                          + game.getJSON() + ")</script>\n");
             writer.flush();

     event.getCometContext().resumeCometHandler(this);
            }
        }
                                                                34
Step 3: Add CometHandler to CometContext
The Servlet Get (called by client initially)
    protected void doGet(HttpServletRequest request,
HttpServletResponse response)
            throws ServletException, IOException {

   TTTHandler handler = new TTTHandler();
   handler.attach(response);
   CometEngine engine = CometEngine.getEngine();
   CometContext context =
engine.getCometContext(contextPath);
   context.addCometHandler(handler);
    }
 The GET is now suspended, awaiting further action
   before a response is returned

                                                       35
Step 4: Advertise Changes
• POST is called via a click on one client
• We get the context again, and call
  context.notify(null) on server
• This sends a NOTIFY event to the handler
• The handler will now update all listening clients
  > Sends a script which includes JSON formatted data
  > Closes all open connections when done.




                                                        36
Step 4: Advertise Changes
Post is called (client)
<table>
<tr>
<td id="cell0"><img id="img0" src="resources/0.gif"
onclick=postMe("0")></td>
...
</table>
var url = "TTTComet1";
function postMe(arg) {
...
     var xhReq = new createXMLHttpRequest();
     xhReq.open("POST", url, true);
     xhReq.setRequestHeader("Content-Type",
             "application/x-www-form-urlencoded");
     xhReq.send("cell="+arg);
};
                                                 37
Step 4: Advertise Changes
Post is called (server)
  protected void doPost(HttpServletRequest
  request, HttpServletResponse response)
              throws ServletException,
  IOException {

  String cellStr = request.getParameter("cell");
  PrintWriter writer = response.getWriter();
  ......
  game.turn(cell);
  ......
  CometEngine engine = CometEngine.getEngine();
  CometContext<?> context =
     engine.getCometContext(contextPath);
  context.notify(null); //attachment for CometEvent
                                                      38
Step 5: Client Side update (called from
Server Side onEvent() in CometHandler)
function chImg(args) {
var data = eval(args);
  // redraw the board
  for (i = 0; i < 9; i++) {
      document.getElementById("img"+i).src=
            "resources/"+data.board[i]+".gif";
  }
// -1 is unfinished, 0 is tie, 1 is X win, 2 is O
win
  var statusMsg;
  if (data.win == 0) {
     statusMsg = "It's a tie!";
  } else if (data.win == 1) {
....
 document.getElementById("gstatus").innerHTML =
statusMsg;
                                                    39
  CometHandler: TTTHandler (revisit)
//Inside the TTTComet Servlet class...
private class TTTHandler implements
CometHandler<HttpServletResponse> {
  private HttpServletResponse response;
//When a push operation happens, onEvent invoked after
CometContext.notify() is called
  public void onEvent(CometEvent event) throws IOException
{
       if (CometEvent.NOTIFY == event.getType()) {
             PrintWriter writer = response.getWriter();
             writer.write(
             "<script type='text/javascript'>parent.chImg("
                          + game.getJSON() + ")</script>\n");
             writer.flush();

        event.getCometContext().resumeCometHandler(this);
            }
       }                                                    40
Sample JSON output

 { “win”: “-1”,
   “board”: [“0”, “1”, “10”,
         “0”, “1”, “10”,
         “1”, “10, “0” ],
   “turn”: “10” }




                               41
Two Player Game:
Tic Tac Toe Demo




                   42
Agenda
• Web 2.0
• Introduction to Comet
• Asynchronous HTTP and the Server
• Develop a Two Player Game using Comet
  (demo)
• Develop a Slideshow Chat Application using
  Cometd (demo)
• Summary and Resources




                                               43
 What Is Cometd?
• HTTP-based event routing bus using
  > Bayeux Protocol
  > Comet as underlying push technology
• Consists of a protocol spec called Bayeux,
  JavaScript technology libraries
  (DOJO toolkit), and an event router
• The Server uses async techniques to “park”
  the request without blocked threads
• Comet programming is easy, cometd is
  even easier
  > No server-side elements need to be created


                                                 44
 What Is the Bayeux Protocol?
• Bayeux is a negotiated, multi-transport,
  JSON-based protocol for publish/subscribe
  asynchronous messaging between:
  > Web browser and server
  > Web browser and web browser
  > http://svn.xantus.org/shortbus/trunk/bayeux/bayeux.html
• Part of the Dojo Cometd project
  > http://cometdproject.dojotoolkit.org/
• Multiple server implementations
  > JavaScript programming language, Java™ programming
    language, perl, python


                                                              45
Bayeux/Cometd
JSON Publish/Subscribe
[
    {
        "channel": "/some/name",
        "clientId": "83js73jsh29sjd92",
        "data": { "myapp" : "specific data", value: 100 }
    }
]
• JSON Messages are published on specified channels
• Channel operations: connect, subscribe, unsubscribe,
  etc.
• Server-side reflector with no server-side application
  needed

                                                            46
Cometd: Enable Comet
• Enable Comet in GlassFish (same as before)
  > domain.xml
  <property name="cometSupport" value="true"/>
• Enabling Bayeux in GlassFish
  > web.xml
  <servlet-mapping>
    <servlet-name>Grizzly Cometd Servlet</servlet-
    name>
    <url-pattern>/cometd/*</url-pattern>
  </servlet-mapping>



                                                     47
  Step1 : Initialize
                                                       Comet Server
dojo.require("dojox.cometd");


//Initialize a connection to the given Comet server:
the GlassFish Grizzly Bayeux servlet

dojox.cometd.init("serverURL");




                                                                      48
  Step 2: Subscribe
dojox.cometd.subscribe(“topic”, "remote topic", "callbackFunction");
                                              Comet Server
 • Subscribes the client to the
   topic channel
 • Any time a message is sent to
   the topic channel the
   callback will be invoked




                                                       Client 2
                              Client 1



                                                                  49
  Step 3: Publish                                                 JSON message

dojox.cometd.publish("topic", {slide: url});                         Comet Server


a client publishes the next slide url to the topic channel



                                       new slide url




                                                       client 1




                                                                                    50
Step 4: Update Clients: CallBack Invoke
                                                               Comet Server

    callBackFunction(slideUrl){
        slide.innerHTML ="<img src='" + slideUrl + "'/>";
    ...
    }
                                            Update Browser
●The callback function is                                        Update Browser
called with the published
message when a new
message is received
●This callback function
updates the browser
content
    ● html img tag with the

      slide url from the         Client 2                    Client 3
      published message

                                                                              51
Slideshow Chat Demo
http://weblogs.java.net/blog/caroljmcdonald/archive/2
008/07/comet_slideshow.html




                                                  52
Agenda
• Web 2.0
• Introduction to Comet
• Asynchronous HTTP and the Server
• Develop a Two Player Game using Comet
  (demo)
• Develop a Slideshow Chat Application using
  Cometd (demo)
• Summary and Resources




                                               53
Servlet 3.0
Future Asynchronous Standard
• Defined by JSR-315 Expert Group
• DWR, Jetty, Tomcat, GlassFish project, and
  ICEfaces participants
• Standard asynchronous processing API being
  defined
  > Asynchronous I/O, Suspendible requests
• Will improve portability of DWR, Cometd, and
  ICEfaces
• Servlet 3.0 will supports only a subset of Comet
  > No pushing functionalities
  > No delivery guarantee
• But unless you write Servlets today, this API will be
 hidden by your chosen Ajax framework                     54
What is Project Atmosphere
 Extends and improve the Grizzlet concept....
• Comet techniques aren't standardized among Web
  Container
  > Grizzly Comet applications aren't portable (cannot run on
    Tomcat nor Jetty)
• Atmosphere
  > a POJO based framework using Inversion of Control (IoC)
    to bring Comet to the masses
  > A framework which can run on any Java based Web Server
  > Run on top of Servlet 2.5 compliant Web Server
• Grizzlet is a POJO based approach for writing
  Comet application
  > Grizzlet only runs on top of the Grizzly Comet Framework
    right now
  > Grizzly community asked many times to have the concept
    ported to other Web Server
• Evolve the Grizzlet...and make it the core of Project
  Atmosphere
                                                                55
Summary
The Asynchronous Web Revolution is Now
• The Asynchronous Web will revolutionize human
    interaction
•   Push can scale with Asynchronous Request
    Processing
•   Writing Games is not that complicated
•   With GlassFish project and Project Grizzly, the
    revolution begins with your application today!
•   Get ready for Atmosphere and Servlet 3.0



                                                      56
For More Information
• Getting Started with GlassFish and Comet
  > http://weblogs.java.net/blog/jfarcand/archive/2008/04/the_hitchhikers
    .html
  > http://weblogs.java.net/blog/jfarcand/archive/2006/10/writting_a_com
    e.html
• Grizzly Active’s Bloggers:
  > Alexey: http://blogs.sun.com/oleksiys/
   > Shing Wai: http://blogs.sun.com/swchan/
   > John: http://weblogs.java.net/blog/johnmann/
   > Sebastien: http://www2.sebastiendionne.ca
   > Jeanfrancois: http://weblogs.java.net/jfarcand
• Project Grizzly
  > http://grizzly.dev.java.net
   > dev@grizzly.dev.java.net & users@dev.grizzly.java.net
                                                                        57
Tao Michael Li
Technology Evangelist




                        58

								
To top