且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测tomcat servlet中的客户端断开连接?

更新时间:2022-10-15 14:23:08


有没有办法可以在不写任何数据的情况下检测到这个


不,因为没有在TCP / IP中检测它而不写任何数据的方法。



不要担心。只需完成请求操作并编写响应即可。如果客户端已经消失,那将导致IOException:connection reset,它将被抛入servlet容器中。你无需做任何事情。


How can I detect that the client side of a tomcat servlet request has disconnected? I've read that I should do a response.getOutputStream().print(), then a response.getOutputStream().flush() and catch an IOException, but is there a way I can detect this without writing any data?

EDIT:

The servlet sends out a data stream that doesn't necessarily end, but doesn't necessarily have any data flowing through it (it's a stream of real time events). I need to actually detect when the client disconnects because I have some cleanup I have to do at that point (resources to release, etcetera). If I have the HttpServletRequest available, will trying to read from that throw an IOException if the client disconnects?

is there a way I can detect this without writing any data?

No because there isn't a way in TCP/IP to detect it without writing any data.

Don't worry about it. Just complete the request actions and write the response. If the client has disappeared, that will cause an IOException: connection reset, which will be thrown into the servlet container. Nothing you have to do about that.