如何检测客户端发起的“取消”操作在 HttpServlet 中的 doGet 期间在服务器端?

发布于 2024-12-22 03:36:07 字数 1129 浏览 1 评论 0原文

我有一个在 Tomcat 上运行的简单 HttpServlet,它提供一个 3.5M 长的文本文件。

我正在从 iOS 访问 servlet(使用 ASIHTTPRequest),并且在 2 秒后(即在所有数据到达之前很久...)执行“取消”操作,

在客户端,我绝对可以看到事务确实被取消了。

问题是我没有任何简单的方法可以在服务器端了解这一点,因此,servlet 看起来总是发送完整的 3.5M。

我本来期望出现类似异常的情况,但它没有发生...

servlet 代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
  int read = 0;
  int total = 0;

  try
  {
    response.setContentType("text/html");
    ServletContext ctx = getServletContext();
    InputStream is = ctx.getResourceAsStream("/WarAndPeace.html");

    byte[] bytes = new byte[1024];
    OutputStream os = response.getOutputStream();

    while ((read = is.read(bytes)) != -1)
    {
      os.write(bytes, 0, read);
      total += read;
    }

    os.flush();
    os.close();
    is.close();
  }
  catch (Exception e)
  {
    // NEVER REACHED
  }

  /*
   * THIS PART IS ALWAYS REACHED WITH total = 3.5M BYTES
   * NO MATTER IF THE CONNECTION WAS CANCELED ON THE CLIENT-SIDE
   *
}

有任何线索吗?谢谢!

注意:我还尝试了正确取消的 NSURLConnection (而不是 ASIHTTPRequest),但结果是相似的。

I have a simple HttpServlet running on Tomcat, which serves a 3.5M long text file.

I'm accessing the servlet from iOS (using ASIHTTPRequest) and I'm doing a "cancel" after 2 seconds (i.e. long before all the data has arrived...)

On the client-side, I can definitely see that the transaction is indeed canceled.

The problem is that I don't have any trivial way to be aware of that on the server-side, and therefore, it looks like the servlet is always sending the full 3.5M.

I would have expected something like an exception, but it's not happening...

The servlet code is as follows:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
  int read = 0;
  int total = 0;

  try
  {
    response.setContentType("text/html");
    ServletContext ctx = getServletContext();
    InputStream is = ctx.getResourceAsStream("/WarAndPeace.html");

    byte[] bytes = new byte[1024];
    OutputStream os = response.getOutputStream();

    while ((read = is.read(bytes)) != -1)
    {
      os.write(bytes, 0, read);
      total += read;
    }

    os.flush();
    os.close();
    is.close();
  }
  catch (Exception e)
  {
    // NEVER REACHED
  }

  /*
   * THIS PART IS ALWAYS REACHED WITH total = 3.5M BYTES
   * NO MATTER IF THE CONNECTION WAS CANCELED ON THE CLIENT-SIDE
   *
}

Any clues? Thanks!

N.B. I also tried with a properly-canceled NSURLConnection (instead of ASIHTTPRequest), but the results are similar.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文