Lightstreamer

Server-Centric Comet With ItsNat

by Jose Maria ArranzOctober 7th, 2008

In this article we are going to introduce the two different development approaches for Comet, client-centric and server-centric, and how ItsNat, in spite of its server-centric nature, is familiar for any JavaScript developer. Also explained are two Comet transports for applications in ItsNat: polling (timers) and long-polling.

Client-Centric Style

In the client-centric style, client to server interactions are driven by JavaScript code executed in the client. Client code is the protagonist of the Comet application because the server usually serves data (JSON, custom XML or JavaScript objects) to the browser and the conversion to markup (if needed) is done in the browser directly with DOM APIs or indirectly with a JavaScript framework. In summary, data models are replicated in the server and in the client and visual state (DOM tree of the page) is only managed in the client.

Client Centric

Google Web Toolkit is considered a client centric framework, it may seem different to the previous scenario because the code is in Java, but GWT is basically a sophisticated tool to convert Java code into JavaScript. The application is coded in Java, but is executed in the browser as JavaScript. In fact server code (executed on the server for instance to query a database) is called using RPC and a GWT built-in bridge is used to transport and convert Java objects (server) to JavaScript objects (“Java” objects on the client) and alternative transport techniques such as JSON can be used.

Server-Centric Style

In the server-centric style, like the Comet add-on for JSF that is present in IceFaces, JavaScript is used in the client, of course, but this code is generated under the hood by the framework. The protagonist from a developer viewpoint is the server code. Following the IceFaces example, a Comet interaction usually implies some kind of change in the state of data models of the JSF components involved in the Comet process. The server re-renders any required component pushing markup changes to the browser updating the visual state of those components. Visual rendering is limited by the rules imposed by the JSF components, and user defined components are possible but they are beyond the capabilities of the average developer.

Server Centric (JSF)

The ItsNat Style

ItsNat approach for Comet is server-centric like JSF, but with a client-centric style of coding, providing a mix of both worlds. This is a direct consequence of the simulation of a Java W3C browser in the server where the browser is mainly “passive”, treated like a sophisticated terminal or GUI renderer of the server. As Java W3C DOM APIs are used for the view logic, templates can be pure X/HTML/SVG files.

In a client-centric Comet application, server data and visual state (DOM tree in the browser) are in different memory spaces so some kind of data transport and conversion must be defined to send server data to the client. Visual rendering of this data is in the client calling DOM APIs.

With ItsNat, the data model and DOM tree (visual state) are in the same memory space, the JVM memory. When the data model changes the related ItsNat component automatically modifies the markup (DOM subtree) associated to this data model in the server, in the same time the framework queues any DOM change in a JavaScript form behind the scenes, pending updates to be sent to the browser.

One advantage of this approach is that no data transport and conversion between Java (or any JVM language) and JavaScript is needed to send data to the client, because the browser is updated automatically by the framework and only visual information (DOM APIs calls) are sent. Furthermore, server data models and ItsNat components are not needed because Java W3C APIs can be directly used with the same style of programming as in DHTML.

The following table summarizes these three approaches:

  Main Program Main Language Data Model Visual Management Layout Control
Client Centric In client JavaScript In server & client In client Full (DOM APIs)
Server C. JSF In server JVM based In server In server Limited
Server C. ItsNat In server JVM based In server In server Full (DOM APIs)

Basic Infrastructure for Comet in ItsNat

When a new web page is loaded by ItsNat, an ItsNatDocument object is automatically created based on the specified HTML template in the load request (usually a URL) and dispatched to a user defined object implementing ItsNatServletRequestListener, this interface mimics the method HttpServlet.doGet or doPost but inside the ItsNat environment.

The ItsNatDocument object is central because it contains and manages an org.w3c.dom.Document object, the DOM tree of the page. Any change to this tree is sent to the client after the load phase and when an Ajax event (usually a DOM event) is processed.

As mentioned, any DOM tree change in the server (or user defined JavaScript submitted calling ItsNatDocument.addCodeToSend(Object)) is queued as JavaScript is ready to be sent to the client. Queued code is sent to the client (and the queue is cleared) as the response of any Ajax request is received by the document/page in the server. Therefore nothing prevents a non-web thread, or a thread associated with an Ajax request targeting another document, from asynchronously changing the server DOM state of the document or queuing custom JavaScript code to be sent to the client when an Ajax request arrives to the server.

Ajax requests are usually client DOM events transported to the server and converted in W3C DOM Event objects. Only a client DOM event is sent to the client if a server DOM event listener was registered associated to the symmetric DOM node in the server.

To register a DOM listener in the server listening client events, ItsNatDocument provides methods like addEventListener*, these are very similar to org.w3c.dom.events.EventListener.addEventListener* methods.

For instance this minimalist example executes a JavaScript alert when the page area is clicked:

1
2
3
4
5
6
7
8
9
10
11
12
13
final ItsNatDocument itsNatDoc = ...;
 
EventListener listener = new EventListener()
{
    public void handleEvent(Event evt)
    {
        itsNatDoc.addCodeToSend("alert('Clicked!');");
    }
};
 
HTMLDocument doc = (HTMLDocument)itsNatDoc.getDocument();
HTMLBodyElement body = (HTMLBodyElement)doc.getBody();
itsNatDoc.addEventListener((EventTarget)body,"click",listener,false);

Where Event, HTMLDocument, HTMLBodyElement and EventTarget are W3C DOM interfaces.

Comet Techniques in ItsNat

ItsNat uses normal Ajax for Comet, Ajax is widespread and supported by all modern browsers including mobile versions. Other alternatives are not currently supported including forever-frames (too hacky for our taste), multipart Ajax requests (not standardized or widely adopted), or WebSockets (too new).

There are two built-in Comet techniques used in ItsNat:

  1. Polling (Ajax Timers in ItsNat terminology)
  2. Long-polling (”Comet” in ItsNat terminology)

Polling/Ajax Timers

In ItsNat a “timer event” is an extension of the W3C DOM Events standard. That is, a timer event is an ItsNat defined Java object implementing the interface org.w3c.dom.events.Event and org.itsnat.core.event.ItsNatTimerEvent (this interface adds some specific methods), and the event type is “itsnat:timer” (this type is only used internally by the framework).

ItsNat timers are the adaptation of the java.util.Timer API to the W3C DOM Events standard and to the web. The interface org.itsnat.core.ItsNatTimer has very similar methods (parameters and behavior) to java.util.Timer.scheduled* methods.

The following example adds a message to the bottom of the page (”Tick”) every 2 seconds, and the first execution is delayed 1 second.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 ItsNatDocument itsNatDoc = ...;
 
EventListener listener = new EventListener()
{
    public void handleEvent(Event evt)
    {
        ItsNatTimerEvent timerEvt = (ItsNatTimerEvent)evt;
        ItsNatDocument itsNatDoc = timerEvt.getItsNatDocument();
        HTMLDocument doc = (HTMLDocument)itsNatDoc.getDocument();
        Element p = doc.createElement("p");
        p.appendChild(doc.createTextNode("Tick"));
        doc.getBody().appendChild(p);
   }
};
 
ItsNatTimer timer = itsNatDoc.createItsNatTimer();
ItsNatTimerHandle handle = timer.schedule(null,listener,1000,2000);
 
System.out.println("Scheduled task started, first time: " + new Date(handle.getFirstTime()) + " period: " + handle.getPeriod());

As in java.util.Timer, there are two types of methods:

  1. Fixed-delay (ItsNatTimer.schedule(…) methods)

    Each execution is scheduled relative to the actual execution time of the previous execution.

  2. Fixed-rate (ItsNatTimer.scheduleAtFixedRate(…) methods)

    Each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (network delay, long event processing, garbage collection etc), two or more executions will occur in rapid succession to “catch up.” This mode may be, inaccurately, called real-time (actually near real-time, true real-time needs a real-time infrastructure that is not currently possible on the web).

Long-Polling

Anyone involved in Comet technology knows how this technique works. In summary, an Ajax request is retained until some change in the server occurs (and the client need to be notified), then the Ajax request is released, the client is updated and automatically a new Ajax request is sent to the client to be retained again.

The protagonist in ItsNat is the interface CometNotifier. Before explaining how this interface works we need to introduce the ClientDocument interface. A ClientDocument object represents the browser page in the client. This may sound confusing because the ItsNatDocument also represents the client page. It makes more sense when “remote view/control” in ItsNat is explained. In brief, the DOM tree contained in an ItsNatDocument can be replicated in several browser pages. There is one single document in the server but many client documents. Associated with any ItsNatDocument is the ClientDocument “owner”, an object that represents the browser page that created and loaded the server document. This object is obtained by calling ItsNatDocument.getClientDocumentOwner().

A CometNotifier instance is created by calling ClientDocument.createCometNotifier() and represents a “Comet Session”. JavaScript is automatically sent to the client to initiate a Comet conversation with the server. The Comet session lives until the method stop() is called or the parent ItsNatDocument is invalidated (for instance when the user closes the page). In theory several Comet sessions can be created associated to the same ClientDocument (same browser page), but in practice it does not make much sense.

The most important method is CometNotifier.notifyClient(). This method notifies the framework that the client must be updated, the retained Ajax is released and any pending DOM change and queued custom JavaScript is sent to the client.

The following is a complete example of a Comet session where a background thread adds to the client page bottom a message (”Tick”) every 2 seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
final ItsNatDocument itsNatDoc = ...;
 
final CometNotifier notifier = 
              itsNatDoc.getClientDocumentOwner().createCometNotifier();
Thread backgroundThr = new Thread()
{
    public void run()
    {
        long t1 = System.currentTimeMillis();
        long t2 = t1;
        do
        {
            try
            {
            Thread.sleep(2000);
            }
            catch(InterruptedException ex) { }
            if (!notifier.isStopped())
            {
                synchronized(itsNatDoc)
                {
                    HTMLDocument doc = (HTMLDocument)itsNatDoc.getDocument();
                    Element p = doc.createElement("p");
                    p.appendChild(doc.createTextNode("Tick"));
                    doc.getBody().appendChild(p);
                }
                notifier.notifyClient();
            }
            t2 = System.currentTimeMillis();
        }
        while( (t2 - t1) < 10*60*1000 ); // Max 10 minutes
        notifier.stop();
        System.out.println("Background server task finished");
    }
};
backgroundThr.start();
System.out.println("Background server task started");

You might be asking why synchronized(itsNatDoc) is used? ItsNat synchronizes the ItsNatDocument object in load time before dispatching to the event listeners. Synchronizing this object is the thread safe way to access the document and any child object(s). You can note that CometNotifier.isStopped() and CometNotifier.notifyClient() methods do not need to be synchronized (in spite of CometNotifier, it is an indirect child of ItsNatDocument).

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]
Comet Support by SitePen

5 Responses to “Server-Centric Comet With ItsNat”

  1. Jose Maria Arranz Says:

    Minor correction (an “and” word is missing):

    “ItsNat synchronizes the ItsNatDocument object in load time AND before dispatching to the event listeners”

    ItsNat ensures ItsNatDocument document is synchronized before user code is executed. User code is defined in two places: in load time (before the document/page is delivered to the browser) and event listeners.

  2. Comet Daily » Blog Archive » Is it Raining Comets and Threads… Again? Says:

    [...] I was adding long-polling to ItsNat, I followed the standard approach of one request per thread; this relationship is mandated by the [...]

  3. Comet Daily » Blog Archive » ItsNat v0.6 released. Comet (long-polling) Now Event-Based Says:

    [...] ItsNat version 0.6 has been released, and adds a new event system for Comet using long-polling. When the client is going to be notified that something occurred in the server (the method CometNotifier.notifyClient() has been called), a special Comet DOM event (an extension of W3C DOM) is fired and dispatched to the optional event listener registered on the CometNotifier. [...]

  4. Thangaraj Says:

    Hi,
    I just read ItsNat manual. This is the concept/technology that i expected for last one year. Nice Job.
    Your slide show also mpress me.

    I have been working in ZK framework. It is quite matured. The problem is that zk occupies memory and work around CSS nightmare.

    And currently my team is evaluating Vaadin, it must yet to matured. The problem is that slow loading, slow response, and the especially problem in CSS. Oops It is a very bad nightmare experience. But it has very nice themes. And some components are very matured like Combobox, datebox etc.,

    Now we will talk about ItsNat. Everything seems ok in very complex component like Tree, but where is autocomplete control. Missing?, this is one that i maximum expected from ItsNat.

    Please dont say that should be developed only by developer. It may have appeared without CSS.

    If you develop more components like ZK(without css like already existing components), i would say ItsNat will be a Hero in the ajax world.

    We planned to evaluate ItsNat, After evaluating we will comment on web.

    Regards
    Thangaraj K

  5. Jose Maria Arranz Says:

    Sorry for delaying
    This is not the best place to talk about ItsNat features beyond Comet, anyway you are right ItsNat needs more components, anyway to fill the gap you can use your preferred client framework the chances of ItsNat for hybrid programming are infinite.

    Take a look:
    http://bit.ly/p4sozN
    http://bit.ly/hRrW9N

Leave a Reply



Copyright 2014 Comet Daily, LLC. All Rights Reserved