AsyncContext and I / O error handling (when peer disconnects)

I implement events sent by the server using the servlet 3.0 interface javax.servlet.AsyncContext .

However, I cannot figure out how I should handle I / O errors, such as disabling peer-to-peer communication.

For a given AsyncContext ac = request.startAsync() I can call ac.getResponse().getWriter().print(something) and then ac.getResponse.getWriter().flush() and it works fine. However, when the client disconnects, I do not get an error - even if I attach the listener, its onError method onError not called.

I tested it with both Jetty 8 and Tomcat 7, and it seems that disconnecting from the client is not reported back to the application.

What can be done to detect a communication error?

+4
java-ee tomcat jetty comet
Aug 20 '12 at 14:50
source share
2 answers

The problem is that: ac.getResponse.getWriter().flush() does not throw an IOException

So, to get an error message during an I / O operation, you need to use ServletOutputStream :

 try { ServletOutputStream out = ac.getResponse().getOutputStream(); out.print(stuff); out.flush(); // throws IOException } catch(IOException e) { // handle a error } 
+4
Aug 21 '12 at 9:16
source share

There is an alternative solution, in cases where it is more convenient to use getWriter() .

 PrintWriter out = ac.getResponse().getWriter(); out.print(stuff); out.flush(); // swallows IOException if (out.checkError()) { // handle error or throw out... } 

That is, the PrintWriter class provides a method for receiving write errors later.

+1
Apr 30 '13 at 14:27
source share



All Articles