AsyncContext 和 I/O 错误处理(当对等断开连接时)

Art*_*yom 5 tomcat comet jetty servlet-3.0 jakarta-ee

我正在使用 Servlet 3.0 的javax.servlet.AsyncContext接口实现服务器发送的事件。

但是,我无法理解我应该如何处理对等断开连接等 I/O 错误。

对于给定的AsyncContext ac = request.startAsync(),我可以调用ac.getResponse().getWriter().print(something)然后ac.getResponse.getWriter().flush()它工作正常。但是,当客户端断开连接时,我不会收到错误消息——即使我附加了一个侦听器,onError也不会调用它的方法。

我用 Jetty 8 和 Tomcat 7 对它进行了测试,似乎与客户端的断开连接没有报告给应用程序。

如何检测通信错误?

Art*_*yom 4

问题是:ac.getResponse.getWriter().flush()不抛出IOException

因此,为了在 I/O 操作时获得错误通知,您需要使用ServletOutputStream

try {
   ServletOutputStream out = ac.getResponse().getOutputStream();
   out.print(stuff);
   out.flush(); // throws IOException
}
catch(IOException e) {
   // handle a error
}
Run Code Online (Sandbox Code Playgroud)