Servlet 3.0异步请求 AsyncContext
建立长连接后,如果连接断开。服务器端怎么才能知道。
protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { final String mac = req.getParameter("mac").replaceAll("-", ":"); resp.setContentType("text/html;charset=UTF-8"); resp.setHeader("Cache-Control", "private"); resp.setHeader("Pragma", "no-cache"); req.setCharacterEncoding("UTF-8"); AsyncContext asyncContext = req.startAsync(); Map<String, AsyncContext> map = new HashMap<String, AsyncContext>(); map.put(mac, asyncContext); asyncContext.setTimeout(1000 * 60 * 1000); // --------------------------------------------------------------------------------- PrintWriter pr = resp.getWriter(); hotelData.setStatus(mac, null); try { int n = this.findHandel(mac); List<Handel> handels = new ArrayList<Handel>(); Handel handel = new Handel(); handel.setMac(mac); if (n == -1) { if (Handel.getHandels() != null) { handels = Handel.getHandels(); } handels.add(handel); asyncContexts.add(map); Handel.setHandels(handels); n = this.findHandel(mac); } else { // asyncContexts.remove(asyncContexts.) asyncContexts.remove(this.FindMap(mac)); asyncContexts.add(map); handels = Handel.getHandels(); handels.set(n, handel); // 重新链接时重置消息 } pr.println("connect success."); pr.flush(); } catch (Exception e) { System.out.println("exception1"); e.printStackTrace(); } // --------------------------------------------------------------------------------- asyncContext.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent event) throws IOException { // event.getSuppliedResponse().getWriter().close(); System.out.println("asynContext finished...."); // directoryMaintainer.removeClient(userName, asyncContext); } @Override public void onTimeout(AsyncEvent event) throws IOException { // directoryMaintainer.removeClient(userName, asyncContext); System.out.println("asynContext timeOut...."); } @Override public void onError(AsyncEvent event) throws IOException { // directoryMaintainer.removeClient(userName, asyncContext); System.out.println("asynContext error...."); } @Override public void onStartAsync(AsyncEvent event) throws IOException { System.out.println("asynContext startAsync...."); } }); } catch (Exception ex) { System.out.println("exception"); ex.printStackTrace(); } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器只有等着超时才知道吧。要想知道客户端是否还健在,可以发送心跳包,好像可以借助IP协议发送很简小的心跳包,google下吧。