Writing to a comet stream using tomcat 6.0
Posted
by user301247
on Stack Overflow
See other posts from Stack Overflow
or by user301247
Published on 2010-03-24T22:00:33Z
Indexed on
2010/03/24
22:03 UTC
Read the original article
Hit count: 299
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.
© Stack Overflow or respective owner