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();
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
服务器只有等着超时才知道吧。要想知道客户端是否还健在,可以发送心跳包,好像可以借助IP协议发送很简小的心跳包,google下吧。