今天在测试中无意中看到Tomcat 6的新特性Comet,使用Comet技术可以轻松实现一个Pushlet的功能,让我看了着实兴奋不已,而其官方网站还给出了一个Messenger的例子。
public class ChatServlet extends HttpServlet implements CometProcessor { protected ArrayListconnections = new ArrayList( ); protected MessageSender messageSender = null; public void init ( ) throws ServletException { messageSender = new MessageSender ( ); Thread messageSenderThread = new Thread (messageSender, "MessageSender[" + getServletContext ( ). getContextPath ( ) + "]" ); messageSenderThread. setDaemon ( true ); messageSenderThread. start ( ); } public void destroy ( ) { connections. clear ( ); messageSender. stop ( ); messageSender = null; } /** * Process the given Comet event. * * @param event The Comet event that will be processed * @throws IOException * @throws ServletException */ public void event (CometEvent event ) throws IOException, ServletException { HttpServletRequest request = event. getHttpServletRequest ( ); HttpServletResponse response = event. getHttpServletResponse ( ); if (event. getEventType ( ) == CometEvent. EventType. BEGIN ) { log ( "Begin for session: " + request. getSession ( true ). getId ( ) ); PrintWriter writer = response. getWriter ( ); writer. println ( "\"-//w3c//dtd html 4.0 transitional//en\">" ); writer. println ( "JSP Chat \"#FFFFFF\">" ); writer. flush ( ); synchronized (connections ) { connections. add (response ); } } else if (event. getEventType ( ) == CometEvent. EventType. ERROR ) { log ( "Error for session: " + request. getSession ( true ). getId ( ) ); synchronized (connections ) { connections. remove (response ); } event. close ( ); } else if (event. getEventType ( ) == CometEvent. EventType. END ) { log ( "End for session: " + request. getSession ( true ). getId ( ) ); synchronized (connections ) { connections. remove (response ); } PrintWriter writer = response. getWriter ( ); writer. println ( "