简体   繁体   English

ConnectTimeout是否不总是阻止从inputstream读取?

[英]ConnectTimeout not always blocking reading from inputstream?

In my application, I open UrlConnections, and I set connection timeout. 在我的应用程序中,我打开UrlConnections,并设置连接超时。 Sometimes, the timeout is thrown, but the inputstream is still readable (and do contain data) 有时会抛出超时,但输入流仍然可读(并且确实包含数据)

I successfully reproed this using the following code: 我使用以下代码成功地对此进行了谴责:

    System.setProperty("http.keepAlive", "false");

    long length = 0;

    while (length == 0) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) (new URL("http://www.worldofwargraphs.com").openConnection());
            connection.setConnectTimeout(1); // 1ms
            connection.connect();
        } catch (IOException ex) {
            try {
                byte[] buf = new byte[8196];
                try (InputStream is0 = connection.getInputStream(); InputStream is = new BufferedInputStream(is0, 8196)) {
                    if (is0 != null) {
                        int ret = 0;
                        while ((ret = is.read(buf)) > 0) {
                            length += ret;
                        }
                    }
                }
            } catch (IOException ex2) {
                Logger.getLogger(JavaApplication6.class.getName()).log(Level.SEVERE, null, ex2);
            }
        }
    }

    System.out.println(length);

As you can see in this code, I try to open a connection with a small timeout (1ms) to make sure that the connection timeouts. 如您在此代码中看到的,我尝试以较小的超时时间(1ms)打开连接,以确保连接超时。 Then I try to read the inputstream 然后我尝试读取输入流

The thing is that, sometimes when trying to read the stream I get a java.net.SocketTimeoutException: connect timed out (which is what I would expect), but the loop sometimes ends, displaying the number of bytes read (32912) 事实是,有时在尝试读取流时,我得到一个java.net.SocketTimeoutException: connect timed out (这是我期望的),但是循环有时会结束,显示读取的字节数(32912)

Could anyone explain me why this second behavior sometimes happens ? 谁能解释我为什么有时会发生第二种行为? I tried to google it, but found nothing about this. 我试图用谷歌搜索,但是对此一无所获。

Thanks 谢谢

Your ridiculously short connect timeout expired, but the connection subsequently completed, so you were able to read. 可笑的短连接超时到期,但是连接随后完成,因此您可以读取。 Note that setting a connection timeout doesn't set a read timeout, so the read blocked until data was available. 请注意,设置连接超时不会设置读取超时,因此读取将阻塞,直到有可用数据为止。

EDIT: In any case your code is wrong. 编辑:无论如何您的代码是错误的。 You should set a realistic connect timeout and close the socket if you get it. 您应该设置一个实际的连接超时,并在收到超时后关闭套接字。 Continuing to the read code after a connect exception doesn't make any sense. 连接异常后继续读取代码没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM