lawrenst
2009-06-16 11:05
浏览 287
已采纳

Tomcat comet 代码

最近在研究一下Tomcat 的comet方式,Tomcat已经实现了自己的comet方式,并且提供了一个例子。但自己感觉一知半解,写的代码页跑步起来,有如下几个问题:
1.EventType.READ 和EventType.BEGIN 有什么区别,READ的是干嘛的?
2.谁有比较完整的关于这方面的例子,麻烦发给我一份。lawrenst@126.com

谢谢,非常谢谢。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • wanghaolovezlq 2009-06-16 11:13
    已采纳

    官方网站还给出了一个Messenger的例子。

    1.
    public class ChatServlet
    2.
    extends HttpServlet implements CometProcessor {
    3.

    4.
    protected ArrayList connections =
    5.
    new ArrayList();
    6.
    protected MessageSender messageSender = null;
    7.
    8.
    public void init() throws ServletException {
    9.
    messageSender = new MessageSender();
    10.
    Thread messageSenderThread =
    11.
    new Thread(messageSender, "MessageSender[" + getServletContext().getContextPath() + "]");
    12.
    messageSenderThread.setDaemon(true);
    13.
    messageSenderThread.start();
    14.
    }
    15.

    16.
    public void destroy() {
    17.
    connections.clear();
    18.
    messageSender.stop();
    19.
    messageSender = null;
    20.
    }
    21.

    22.
    /**
    23.
    * Process the given Comet event.
    24.
    *
    25.
    * @param event The Comet event that will be processed
    26.
    * @throws IOException
    27.
    * @throws ServletException
    28.
    */
    29.
    public void event(CometEvent event)
    30.
    throws IOException, ServletException {
    31.
    HttpServletRequest request = event.getHttpServletRequest();
    32.
    HttpServletResponse response = event.getHttpServletResponse();
    33.
    if (event.getEventType() == CometEvent.EventType.BEGIN) {
    34.
    log("Begin for session: " + request.getSession(true).getId());
    35.
    PrintWriter writer = response.getWriter();
    36.
    writer.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
    37.
    writer.println("

    JSP Chat");
    38.
    writer.flush();
    39.
    synchronized(connections) {
    40.
    connections.add(response);
    41.
    }
    42.
    } else if (event.getEventType() == CometEvent.EventType.ERROR) {
    43.
    log("Error for session: " + request.getSession(true).getId());
    44.
    synchronized(connections) {
    45.
    connections.remove(response);
    46.
    }
    47.
    event.close();
    48.
    } else if (event.getEventType() == CometEvent.EventType.END) {
    49.
    log("End for session: " + request.getSession(true).getId());
    50.
    synchronized(connections) {
    51.
    connections.remove(response);
    52.
    }
    53.
    PrintWriter writer = response.getWriter();
    54.
    writer.println("
    打赏 评论
  • zhoujuan520 2009-06-16 11:45
    打赏 评论
  • wanghaolovezlq 2009-06-28 23:11

    朋友,问题要自动关闭啦,结分哦

    打赏 评论

相关推荐 更多相似问题