Sun GlassFish Enterprise Server v3 Prelude Developer's Guide

ProcedureNotifying the Comet Handler of an Event

  1. Add an onEvent method to the CometHandler class to define what happens when an event occurs:

    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.counter.updateCount('" + count + "')" +
    			"</script>\n");
    		writer.flush();
    		event.getCometContext().resumeCometHandler(this);
    	}
    }

    This method first checks if the event type is NOTIFY, which means that the web component is notifying the CometHandler object that a client has incremented the count. If the event type is NOTIFY, the onEvent method gets the updated count, and writes out JavaScript to the client. The JavaScript includes a call to the updateCount function, which will update the count on the clients' pages.

    The last line resumes the Comet request and removes it from the list of active CometHandler objects. By this line, you can tell that this application uses the long-polling technique. If you were to delete this line, the application would use the HTTP-Streaming technique.

    • For HTTP-Streaming:

      Add the same code as for long-polling, except do not include the following line:

      event.getCometContext().resumeCometHandler(this);

    You don't include this line because you do not want to resume the request. Instead, you want the connection to remain open.

  2. Increment the counter and forward the response by adding the following lines to the doPost method:

    counter.incrementAndGet();
    CometEngine engine = CometEngine.getEngine();
    CometContext<?> context = 
    	engine.getCometContext(contextPath);
    context.notify(null);
    req.getRequestDispatcher("count.html").forward(req, res);

    When a user clicks the button, the doPost method is called. The doPost method increments the counter. It then obtains the current CometContext object and calls its notify method. By calling context.notify, the doPost method triggers the onEvent method you created in the previous step. After onEvent executes, doPost forwards the response to the clients.