做網絡開發的想必對setSoTimeout這個方法很熟悉,知道是設置的超時事件。但是很多人都認為這個是設置鏈路的超時時間,但是查看相關文檔的此方法的說明:
HttpConnectionParams:
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.
Socket:
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout,
a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires,
a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect.
The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
DatagramSocket:
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout,
a call to receive() for this DatagramSocket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised,
though the DatagramSocket is still valid. The option must be enabled prior to entering the blocking operation to have effect.
The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
看文檔的詳細說明,很顯然,這種理解是不對的,不是鏈接的超時時間。 簡單概括起來,應該是:讀取數據時阻塞鏈路的超時時間。
上面Socket的setSoTimeout的文檔翻譯后的內容為:
setSoTimeout public void setSoTimeout(int timeout) throws SocketException啟用/禁用帶有指定超時值的 SO_TIMEOUT,以毫秒為單位。將此選項設為非零的超時值時,在與此 Socket 關聯的 InputStream 上調用 read() 將只阻塞此時間長度。 如果超過超時值,將引發 java.net.SocketTimeoutException,雖然 Socket 仍舊有效。選項必須在進入阻塞操作前被啟用才能生效。 超時值必須是 > 0 的數。超時值為 0 被解釋為無窮大超時值。 參數: timeout - 指定的以毫秒為單位的超時值。 拋出: SocketException - 如果底層協議出現錯誤,例如 TCP 錯誤。
最簡單的測試驗證的方法是:
寫一個基於Socket的下載方法,設置setSoTimeout后,下載一個大文件,會發現,下載的時間超過setSoTimeout的值之后,就會失敗!!
