1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package com.acme;
16
17 import java.io.IOException;
18
19 import javax.servlet.ServletException;
20 import javax.servlet.http.HttpServlet;
21 import javax.servlet.http.HttpServletRequest;
22 import javax.servlet.http.HttpServletResponse;
23
24 import org.mortbay.util.ajax.Continuation;
25 import org.mortbay.util.ajax.ContinuationSupport;
26
27
28
29
30
31
32
33 public class CometServlet extends HttpServlet
34 {
35 public void begin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
36 {
37 request.setAttribute("org.apache.tomcat.comet",Boolean.TRUE);
38 }
39
40 public void end(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
41 {
42 synchronized(request)
43 {
44 request.removeAttribute("org.apache.tomcat.comet");
45
46 Continuation continuation=ContinuationSupport.getContinuation(request,request);
47 if (continuation.isPending())
48 continuation.resume();
49 }
50 }
51
52 public void error(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
53 {
54 end(request,response);
55 }
56
57 public boolean read(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
58 {
59 throw new UnsupportedOperationException();
60 }
61
62 protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
63 {
64 synchronized(request)
65 {
66
67
68 Continuation continuation=ContinuationSupport.getContinuation(request,request);
69
70 if (!continuation.isPending())
71 begin(request,response);
72
73 Integer timeout=(Integer)request.getAttribute("org.apache.tomcat.comet.timeout");
74 boolean resumed=continuation.suspend(timeout==null?60000:timeout.intValue());
75
76 if (!resumed)
77 error(request,response);
78 }
79 }
80
81 public void setTimeout(HttpServletRequest request, HttpServletResponse response, int timeout) throws IOException, ServletException,
82 UnsupportedOperationException
83 {
84 request.setAttribute("org.apache.tomcat.comet.timeout",new Integer(timeout));
85 }
86 }