使用Jetty和DWR实现Comet Web应用程序

豆豆网   技术应用频道   2007年08月09日  【字号: 收藏本文

内容摘要:结合使用 Comet 模式(将数据推到客户机)和 Jetty 6 的 Continuations API(将 Comet 应用程序扩展到大量客户机中)。您可以方便地在 Direct Web Remoting (DWR) 2 中将 Comet 和 Continuations 与 Reverse Ajax 技术结合使用。

  接下来,为了模拟对异步事件的等待,清单 2 展示了 BlockingServlet 的 service() 方法,该方法将使用 Thread.sleep() 调用在线程结束之前暂停 2000 毫秒的时间。它还在执行开始和结束时输出系统时间。为了区别输出和不同的请求,还将作为标识符的请求参数记录在日志中。

  清单 2. BlockingServletpublic class BlockingServlet extends HttpServlet {
 public void service(HttpServletRequest req, HttpServletResponse res)
                       throws java.io.IOException {
  String reqId = req.getParameter("id");
  
  res.setContentType("text/plain");
  res.getWriter().println("Request: "+reqId+"  start:  " + new Date());
  res.getWriter().flush();
  try {
   Thread.sleep(2000);
  } catch (Exception e) {}
  
  res.getWriter().println("Request: "+reqId+"  end:  " + new Date());
 }
}

  现在可以观察到 servlet 响应一些同步请求的行为。清单 3 展示了控制台输出,五个使用 lynx 的并行请求。命令行启动五个 lynx 进程,将标识序号附加在请求 URL 的后面。

  清单 3. 对 BlockingServlet 并发请求的输出$ for i in 'seq 1 5' ; do lynx -dump localhost:8080/blocking?id=$i & done
Request: 1   start: Sun Jul 01 12:32:29 BST 2007
Request: 1   end:  Sun Jul 01 12:32:31 BST 2007
Request: 2   start: Sun Jul 01 12:32:31 BST 2007
Request: 2   end:  Sun Jul 01 12:32:33 BST 2007
Request: 3   start: Sun Jul 01 12:32:33 BST 2007
Request: 3   end:  Sun Jul 01 12:32:35 BST 2007
Request: 4   start: Sun Jul 01 12:32:35 BST 2007
Request: 4   end:  Sun Jul 01 12:32:37 BST 2007
Request: 5   start: Sun Jul 01 12:32:37 BST 2007
Request: 5   end:  Sun Jul 01 12:32:39 BST 2007

来源:developerWorks    作者:Philip McCarthy    责编:豆豆技术应用

正在加载评论...