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

http://tech.ddvip.com   2007年08月09日    社区交流

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

  清单 7. ContinuationBasedTracker 结构public GpsCoord getNextPosition(Continuation continuation, int timeoutSecs) {
 synchronized(this) {
  if (!continuation.isPending()) {
   pendingContinuations.add(continuation);
  }
  // Wait for next update
  continuation.suspend(timeoutSecs*1000);
 }
 return (GpsCoord)continuation.getObject();
}
public void onCoord(GpsCoord gpsCoord) {
 synchronized(this) {
  for (Continuation continuation : pendingContinuations) {
   continuation.setObject(gpsCoord);
   continuation.resume();
  }
  pendingContinuations.clear();
 }
}

  当客户机使用 Continuation 调用 getNextPosition() 时,isPending 方法将检查此时的请求是否是第二次执行,然后将它添加到等待坐标的 Continuation 集合中。然后该 Continuation 被暂停。同时,onCoord —— 生成新坐标时将被调用 —— 循环遍历所有处于等待状态的 Continuation,对它们设置 GPS 坐标,并重新使用它们。之后,每个再次执行的请求完成 getNextPosition() 执行,从 Continuation 检索 GpsCoord 并将其返回给调用者。注意此处的同步需求,是为了保护 pendingContinuations 集合中的实例状态不会改变,并确保新增的 Continuation 在暂停之前没有被处理过。

  最后一个难点是 servlet 代码本身,如 清单 8 所示:

  清单 8. GPSTrackerServlet 实现public class GpsTrackerServlet extends HttpServlet {
  private static final int TIMEOUT_SECS = 60;
  private ContinuationBasedTracker tracker = new ContinuationBasedTracker();
 
  public void service(HttpServletRequest req, HttpServletResponse res)
                        throws java.io.IOException {
   Continuation c = ContinuationSupport.getContinuation(req,null);
   GpsCoord position = tracker.getNextPosition(c, TIMEOUT_SECS);
   String json = new Jsonifier().toJson(position);
   res.getWriter().print(json);
  }
}

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

正在加载评论...