开发者社区 问答 正文

Servlet 3.0异步请求 AsyncContext? 400 报错

Servlet 3.0异步请求 AsyncContext? 400 报错

建立长连接后,如果连接断开。服务器端怎么才能知道。

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();
		}
	}

展开
收起
爱吃鱼的程序员 2020-06-04 16:29:19 468 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    服务器只有等着超时才知道吧。要想知道客户端是否还健在,可以发送心跳包,好像可以借助IP协议发送很简小的心跳包,google下吧。

    2020-06-04 17:52:49
    赞同 展开评论
问答标签:
问答地址: