import com.sun.grizzly.comet.*; import com.sun.grizzly.comet.concurrent.DefaultConcurrentCometHandler; import com.sun.grizzly.http.embed.GrizzlyWebServer; import com.sun.grizzly.tcp.http11.GrizzlyAdapter; import com.sun.grizzly.tcp.http11.GrizzlyRequest; import com.sun.grizzly.tcp.http11.GrizzlyResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Main19 { private static class MyCometHander extends DefaultConcurrentCometHandler { public void onEvent(CometEvent event) throws IOException { //To change body of implemented methods use File | Settings | File Templates. } public void onInitialize(CometEvent event) throws IOException { //To change body of implemented methods use File | Settings | File Templates. } } private static class CounterHandler implements CometHandler { private GrizzlyResponse response; private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); public void attach(GrizzlyResponse o) { this.response = o; System.out.println("on attach"); executor.scheduleAtFixedRate(new Runnable() { public void run() { try { CometContext ctx = CometEngine.getEngine().getCometContext("/qwe"); ctx.notify(new Timestamp(System.currentTimeMillis())); } catch (Exception e) { e.printStackTrace(); } } }, 1, 1, TimeUnit.SECONDS); } public void onEvent(CometEvent cometEvent) throws IOException { System.out.println("on onEvent begin: " + cometEvent.getType()); PrintWriter writer = response.getWriter(); writer.print(new Timestamp(System.currentTimeMillis())); writer.flush(); System.out.println("on onEvent end"); } public void onInitialize(CometEvent cometEvent) throws IOException { System.out.println("on initialize"); } public void onTerminate(CometEvent cometEvent) throws IOException { System.out.println("on terminate"); } public void onInterrupt(CometEvent cometEvent) throws IOException { System.out.println("on interrupt"); cometEvent.getCometContext().removeCometHandler(this); } } public static void main(String[] args) throws IOException { final GrizzlyWebServer gws = new GrizzlyWebServer(4343); gws.addAsyncFilter(new CometAsyncFilter()); final CometEngine engine = CometEngine.getEngine(); engine.register("/qwe").setBlockingNotification(false); gws.addGrizzlyAdapter(new GrizzlyAdapter() { @Override public void service(GrizzlyRequest request, GrizzlyResponse response) { CounterHandler handler = new CounterHandler(); handler.attach(response); CometContext context = engine.getCometContext("/qwe"); context.addCometHandler(handler); } }, new String[]{"/qwe"}); gws.start(); } }