Sun GlassFish Enterprise Server v3 Prelude Developer's Guide

ProcedureDefining a Comet Handler to Send Updates to the Client

  1. Create a private class that implements CometHandler and add it to the servlet class:

    private class CounterHandler 
    	implements CometHandler<HttpServletResponse> {
    	private HttpServletResponse response;
    }
  2. Add the following methods to the class:

    public void onInitialize(CometEvent event) 
    	throws IOException {}
    
    	public void onInterrupt(CometEvent event) 
    		throws IOException {
    		removeThisFromContext();
    	}
    	
    	public void onTerminate(CometEvent event) 
    		throws IOException {
    		removeThisFromContext();
    	}
    
    	public void attach(HttpServletResponse attachment) {
                this.response = attachment;
    	}
    
    	private void removeThisFromContext() throws IOException {
    		response.getWriter().close();
    		CometContext context = 
    			CometEngine.getEngine().getCometContext(contextPath);
    		context.removeCometHandler(this);
    	}

    You need to provide implementations of these methods when implementing CometHandler. The onInterrupt and onTerminate methods execute when certain changes occur in the status of the underlying TCP communication. The onInterrupt method executes when communication is resumed. The onTerminate method executes when communication is closed. Both methods call removeThisFromContext, which removes the CometHandler object from the CometContext object.