如何正确检测Servlet规范3客户端断开? [英] How to properly detect a client disconnect in servlet spec 3?

查看:212
本文介绍了如何正确检测Servlet规范3客户端断开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写的反应,是因为没有正确断开回调:

I have tried writing to the response, because there is no proper disconnect callback:

private boolean write(byte[] output, AsyncContext context) {
    try {
        OutputStream stream  = context.getResponse().getOutputStream();
        stream.write(output);
        stream.flush();
        return true;
    } catch (IOException ex) {
        //client disconnected
        log.error(ex);
        removeAsyncContext(context);
        return false;
    }

}

但这似乎并不奏效。当客户端断开,写,刷新缓冲区的没有抛出异常

奇怪的是,你尝试写入(断开之后)输出流第二次写操作抛出异常。它看起来像你写/刷新它,一些内部状态设置为错误,不通知的第一次。

The weird thing is, the second time you try to write to the output stream (after the disconnect), the write does throw an exception. It looks like the first time you write/flush it,some internal state is set to error, without notifying.

我曾尝试在两个码头8和Tomcat 7,我看到相同的行为。

I have tried on both Jetty 8 and Tomcat 7 and I see the same behavior.

有没有办法找出是否是由客户端接收邮件的解决方案?我缺少的东西吗?

Is there a solution to find out whether the message is received by the client? Am I missing something?

推荐答案

我承认你正在寻找的检测断开一个适当的方式,但对于那些谁不介意杂牌组装电脑:

I recognize you are looking for a proper way of detecting disconnects, but for those who don't mind a kludge:

请注意:此方法定期发送空格字符到客户端必须的间preting结果前进行修整。这是kludgey一部分。

Note: This method periodically sends space characters to the client that must be trimmed before interpreting the results. This is the kludgey part.


  1. 启动能够访问servlet响应的作家/ OutputStream的一个线程。此线程定期发送空格字符(我用间隔1秒)到客户端。裹在一个IOException异常try / catch块,设置您的中止标志。

  1. Start a thread that has access to the writer/outputstream of the servlet response. This thread sends space characters periodically (I used 1 second intervals) to the client. Wrap in a IOException try/catch block that sets your abort flag.

如果连接被关闭,大多数的servlet将抛出EOFException类的香料(它是一个IOException)时数据不能被传递到客户端。您正赶上这个异常以及设置中止标志。

If the connection is closed, most servlets will throw a flavor of EOFException (which is an IOException) when data cannot be delivered to the client. You are catching this exception and setting your abort flag.

在中止标志被抓住了,你有选择。您可以核弹执行的线程,把所有的处理定期检查中止标志,推异常到执行的线程,或做任何数量的东西(这里不详述)。

When the abort flag is caught, you have options. You can nuke the executing thread, have all your processing periodically check for the abort flag, push an exception into the executing thread, or do any number of things (not detailed here).

如果处理完成成功,您将获得由若干空格pfixed结果$ P $。再次,记得要修剪这些客户机上。

Should the process finish successfully, you will get your results prefixed by a number of spaces. Again, remember to trim these on your client.

这篇关于如何正确检测Servlet规范3客户端断开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆