The Source for Java Technology Collaboration
User: Password:



Jim Driscoll's Blog

Web Applications Archives


Comet TicTacToe

Posted by driscoll on May 07, 2008 at 06:45 PM | Permalink | Comments (1)

Here's the Comet TicTacToe that I went over in my BOF on Comet on Wednesday night. It's pretty simple (though not as simple as my first example, or even the somewhat improved version) - just 200 lines of Java code (including the game logic), 50 lines of JavaScript (embedded in an HTML page), 50 lines of HTML, and a 75 line CSS file. Simple stuff, but if you're looking to write your own Comet app, this might help get you started.

You can find the full Netbeans project here.

Essentially, the program logic is contained in only two files: ttt1.html, and CometServlet.java. Check 'em out. After my initial example two posts ago, these should be pretty self explanatory. If you have any questions, by all means ask in the comments below.

Solving the Comet timeout problem

Posted by driscoll on May 05, 2008 at 02:07 PM | Permalink | Comments (0)

In my previous blog, I mentioned that I didn't like the hack of reloading the iframe via the post action - it's hacky, and it's not hard to imagine it messing things up in a more complex program.

Turns out the answer is both easy and blindingly obvious once you think of it: the iframe onload event. And while we're add it, we'll add a onerror event too.

In my previous program, I had had a hidden iframe, and on every update, I would reset the source for the iframe using the location property.

We'll still do that, but add a new function:

       <iframe name="hidden" src="CometCount" frameborder="0" height="0" width="100%"
       onload="restartPoll()" onerror="restartPoll()" ></iframe>

Note the onload and onerror events - whenever the server closes the connection, these will be called. And here's the function that's called:

            var retries = 0;
            function restartPoll() {
                if (retries++ > 10) {
                    alert("The connection has errored out too many times");                    
                } else {
                    hidden.location = url;                    
                }
            }

Also, I've added a retry limit in there - it wouldn't do to have the client go into a fatal spin just because the server is down.

Now when the server closes the connection (from a timeout, or an error), the client will continue to function, automatically calling back into the server. Not a solution you'll want for every situation, but useful enough, especially for our small example.

Lastly, there was a bug in my previous version under IE - sorry about that. It turns out that if you send a POST via IE, you need to have a content body, or IE gets fussy. The fix is to change the line

            xhReq.send(null);
to
            xhReq.send("null");
I've uploaded new versions of the files index.html and CometCount.java, so you can see the complete code in context.

Dead Simple Comet Example on Glassfish v3 / Grizzly

Posted by driscoll on May 01, 2008 at 03:02 PM | Permalink | Comments (2)

I was looking at a recent blog by Shing Wai Chan and going through the Comet example, when I noticed that the example wasn't working correctly. Although he updated his example to get around that problem, I was still a bit unsatisfied, and decided to sit down, using his basic example, and see if I could make it even simpler.

I've whittled it down to about 100 lines, and only 2 files, and I thought I'd go over it here. The full example (both files) are index.html and CometCount.java. So this will be a little long, but if you're tired of reading my rambling, just look at the files, and the code should speak for itself.

First, about the app: It's a simple counter, which is updated every time you hit a button on the page. Pretty basic, except - every other web browser viewing that page will have the counter updated as well, through the magic of Comet.

About setting it up: make sure that the url mapping points to /CometCount, the value is hardcoded in a few places. Also, to compile you'll need access to the Grizzly Comet APIs - you can either get them from Grizzly, or Glassfish v3 tp2. You'll need to also add the jar in the modules directory named grizzly-optionals to your classpath in order to build, along with the standard Servlet API. You'll also need to update the domain.xml of the v3 instance to add the property cometSupport=true, as you see below:

        <http-listener acceptor-threads="1" address="0.0.0.0" 
           blocking-enabled="false" default-virtual-server="server"
           enabled="true" family="inet" id="http-listener-1" port="8080"
           security-enabled="false" server-name="" xpowered-by="true">
                <property name="cometSupport" value="true"/>
        </http-listener>

Now on to the description of the program flow. On startup, the servet is initialized, and registers itself with with the Comet Engine (make sure the servlet is installed with a url CometCount, or it won't work). We set a timeout of 2 minutes.

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext context = config.getServletContext();
        contextPath = context.getContextPath() + "/MyComet";
        
        CometEngine engine = CometEngine.getEngine();
        CometContext cometContext = engine.register(contextPath);
        cometContext.setExpirationDelay(120 * 1000);
    }

Then on the first load of index.html in the browser, the hidden iframe makes a call to the doGet of the servlet - this call suspends, awaiting further action. It does this by attaching the response to a handler (of type CounterHandler), and attaching the handler to the servlet's CometContext. This also gives rise to the first bug of the program - there's no display of initial result.

So this:
<iframe name="hidden" src="CometCount" frameborder="0" height="0" width="100%"></iframe>
calls this:
   protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        
        CounterHandler handler = new CounterHandler();
        handler.attach(res);
        
        CometEngine engine = CometEngine.getEngine();
        CometContext context = engine.getCometContext(contextPath);
        
        context.addCometHandler(handler);
    }

Next, someone, somewhere, who's also using the program, hits the button marked "click". This calls the onclick method, postMe(). postMe sends an empty POST to the servlet, triggering the doPost method.

So this:
<input type="button" onclick="postMe();" value="Click">
Calls this:
            var url = "CometCount";
            function postMe() {
                function createXMLHttpRequest() {
                    try { return new XMLHttpRequest(); } catch(e) {}
                    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
                    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
                    alert("Sorry, you're not running a supported browser - XMLHttpRequest not supported");
                    return null;
                };
                var xhReq = new createXMLHttpRequest();
                xhReq.open("POST", url, false);
                xhReq.send(null);
                hidden.location = url;
            };

The doPost method increments the counter, and then sends a notify event to the servlet's CometHandler.

    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        counter.incrementAndGet();
        
        CometEngine engine = CometEngine.getEngine();
        CometContext context = engine.getCometContext(contextPath);
        context.notify(null);
    }

This event now wakes up that initial GET request, and sends a bit of javascript down the line. Lastly, we call resumeCometHandler, which marks the current event as completed, removing it from the active queue.

        public void onEvent(CometEvent event) throws IOException {
            if (CometEvent.NOTIFY == event.getType()) {
                int count = counter.get();
                PrintWriter writer = response.getWriter();
                writer.write("<script type='text/javascript'>parent.updateCount('" + count + "')</script>\n");
                writer.flush();
                event.getCometContext().resumeCometHandler(this);
            }
        }

Back at the client, that javascript that got sent down gets put into the hidden iFrame, and then executed. This calls the updateCount function, which updates the counter with the new value. Then, we set the iframes' location object, which reconnects with GET to the servlet, and we're ready for our next request.

            function updateCount(c) {
                document.getElementById('count').innerHTML = c;
                hidden.location = url;
            }

That is, unless we time out. If we time out (remember, we set the timeout to 2 minutes, not "infinite"), the iframe goes dead, the GET polling loop is broken, and we never again update the counter on the webpage, though the user's increasing frustrated button pushing on the client will happily update counter on the server. So, to get around this, we add a single line at the end of our postMe function, updating the hidden iframe's location again. This is the one really hacky part of the program, and I'd love to know a better way to do it. Also, it gives rise to the second bug of our program, related to the first - if the connection dies, you need to click the button twice to see an update of the counter on the client.

So - ta da! We have a bare bones, long polling comet application in two files and about 100 lines.

Again, here's the programs Download file index.html Download file CometCount.java

Jeanfrancois Arcand and I have a BOF on Wednesday night (May 7th, 2008) at JavaOne. If you're at JavaOne and are just getting started with Comet, come on by.

JSF Datatable Howto

Posted by driscoll on March 12, 2008 at 10:59 AM | Permalink | Comments (1)

I'm currently learning JSF, and wanted to give a little Google link love to a really great guide to learning JSF's use with databases, especially the datatable component. The JSF Database Howto written by BalusC is a great getting started guide to using datatables with JSF, and if this is something you're looking for, check it out... It's quite literally better than any of the books on JSF that I've read on this topic.



Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds