Writing to a comet stream using tomcat 6.0
Hey I'm new to java servlets and I am trying to write one that uses comet so that I can create a long polling Ajax request. I can successfully start the stream and perform operations but I can't write anything out. Here is my code:
public class CometTestServlet extends HttpServlet implements CometProcessor {
/**
*
*/
private static final long serialVersionUID = 1070949541963627977L;
private MessageSender messageSender = null;
protected ArrayList<HttpServletResponse> connections = new ArrayList<HttpServletResponse>();
public void event(CometEvent cometEvent) throws IOException, ServletException {
HttpServletRequest request = cometEvent.getHttpServletRequest();
HttpServletResponse response = cometEvent.getHttpServletResponse();
//final PrintWriter out = response.getWriter();
if (cometEvent.getEventType() == CometEvent.EventType.BEGIN) {
PrintWriter writer = response.getWriter();
writer.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
writer.println("<head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
writer.println("</body></html>");
writer.flush();
cometEvent.setTimeout(10 * 1000);
//cometEvent.close();
} else if (cometEvent.getEventType() == CometEvent.EventType.ERROR) {
log("Error for session: " + request.getSession(true).getId());
synchronized(connections) {
connections.remove(response);
}
cometEvent.close();
} else if (cometEvent.getEventType() == CometEvent.EventType.END) {
log("End for session: " + request.getSession(true).getId());
synchronized(connections) {
connections.remove(response);
}
PrintWriter writer = response.getWriter();
writer.println("</body></html>");
cometEvent.close();
开发者_高级运维 } else if (cometEvent.getEventType() == CometEvent.EventType.READ) {
//handleReadEvent(cometEvent);
InputStream is = request.getInputStream();
byte[] buf = new byte[512];
do {
int n = is.read(buf); //can throw an IOException
if (n > 0) {
log("Read " + n + " bytes: " + new String(buf, 0, n)
+ " for session: " + request.getSession(true).getId());
} else if (n < 0) {
//error(cometEvent, request, response);
return;
}
} while (is.available() > 0);
}
}
Any help would be appreciated.
If you're new to servlets and trying to run Comet code on Tomcat, a good start is to run the example code from http://tomcat.apache.org/tomcat-6.0-doc/aio.html.
Very very important (from that page) is "IMPORTANT NOTE: Usage of these features requires using the APR or NIO HTTP connectors. The classic java.io HTTP connector and the AJP connectors do not support them."
If you don't configure your Tomcat instance to use NIO instead of the plain HTTP connector, Comet will not work.
精彩评论