Detecting client disconnect in tomcat servlet?

后端 未结 3 790
青春惊慌失措
青春惊慌失措 2020-11-28 14:08

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.getOutp

相关标签:
3条回答
  • 2020-11-28 14:23

    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.

    0 讨论(0)
  • 2020-11-28 14:26

    Have you tried to flush the buffer of the response: response.flushBuffer(); Seems to throw an IOException when the client disconnected.

    0 讨论(0)
  • 2020-11-28 14:39

    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).

    There the finally block is for. It will be executed regardless of the outcome. E.g.

    OutputStream output = null;
    try {
        output = response.getOutputStream();
        // ...
        output.flush();
        // ...
    } finally {
        // Do your cleanup here.
    }
    

    If I have the HttpServletRequest available, will trying to read from that throw an IOException if the client disconnects?

    Depends on how you're reading from it and how much of request body is already in server memory. In case of normal form encoded requests, whenever you call getParameter() beforehand, it will usually be fully parsed and stored in server memory. Calling the getInputStream() won't be useful at all. Better do it on the response instead.

    0 讨论(0)
提交回复
热议问题