![](/img/trans.png)
[英]Reading from InputStream - non-blocking with busy waiting VS blocking with timeout?
[英]ConnectTimeout not always blocking reading from inputstream?
在我的應用程序中,我打開UrlConnections,並設置連接超時。 有時會拋出超時,但輸入流仍然可讀(並且確實包含數據)
我使用以下代碼成功地對此進行了譴責:
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);
如您在此代碼中看到的,我嘗試以較小的超時時間(1ms)打開連接,以確保連接超時。 然后我嘗試讀取輸入流
事實是,有時在嘗試讀取流時,我得到一個java.net.SocketTimeoutException: connect timed out
(這是我期望的),但是循環有時會結束,顯示讀取的字節數(32912)
誰能解釋我為什么有時會發生第二種行為? 我試圖用谷歌搜索,但是對此一無所獲。
謝謝
可笑的短連接超時到期,但是連接隨后完成,因此您可以讀取。 請注意,設置連接超時不會設置讀取超時,因此讀取將阻塞,直到有可用數據為止。
編輯:無論如何您的代碼是錯誤的。 您應該設置一個實際的連接超時,並在收到超時后關閉套接字。 連接異常后繼續讀取代碼沒有任何意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.