6

有没有办法找出 HttpServletRequest 是否被中止?

我正在编写一个即时浏览器应用程序(某种聊天):客户端使用 AJAX-HTTP-Requests 在循环中请求新事件。服务器 (Tomcat) 在 HttpServlet 中处理请求。如果此客户端没有新事件,服务器会延迟回复,直到有新事件到达或发生超时(30 秒)。

现在我想识别不再轮询的客户端。因此,我在请求结束时启动了一个 kick-Timer,当新请求到达时它会停止。如果客户端关闭浏览器窗口,TCP-Connection 将关闭,HTTP-Request 将中止。

问题:客户端没有遇到 kick-Timeout,因为 Servlet 仍在处理事件请求 - 休眠并等待事件或超时。

如果我能以某种方式监听连接中止事件,然后通知等待请求以停止它,那就太好了。但我在 HttpServletRequest 或 HttpServletResponse 中找不到类似的东西......

4

3 回答 3

2

这可能不再对 OP 有帮助,但它可能会帮助其他人试图检测 HttpServlet 中终止的 HTTP 连接,因为我遇到了类似的问题并最终找到了答案。

关键是,当客户端取消请求时,通常服务器发现的唯一方法是向客户端发送一些数据,这种情况下会失败。我想检测客户端何时停止等待服务器上的长时间计算,所以我最终通过HttpServletResponse's writer 定期将单个字符写入响应正文。要强制将数据发送到客户端,您必须调用,如果连接中止则HttpServletResponse.flushBuffer()抛出。ClientAbortException

于 2018-07-12T23:25:00.033 回答
1

You are probably using some sort of thread-notification (Semaphores or Object.wait) to hold and release the Servlet threads. How about adding a timeout (~10s) to the wait, then somehow checking whether the connection is still alive and then continuing the wait for another 10s, if the connection is still there.

I don't know whether there are reliable ways to poll the "liveness" of the connection (e.g. resp.getOutputStream not throwing an Exception) and if so, which way is the best (most reliable, least CPU intense).

于 2012-02-20T15:00:04.033 回答
0

看起来等待请求可能会很快降低系统的性能。如果请求保持打开状态,响应请求的线程将很快用完。您可以尝试完成所有请求(如果没有消息,则向您的客户返回“null”),并在后端设置一个线程来跟踪客户轮询以来的时间。该线程可以将客户端标记为不活动。

于 2010-12-06T23:16:22.373 回答