Java設定Client Socket連結Server超時時間
阿新 • • 發佈:2019-01-07
一、錯誤示例
最近在寫socket程式時,偶然發現程式被卡住很長時間,除錯後發現是建立Socket時,採用的方式不對:
Socket s = new Socket(String host, String port);
當採用該方式建立Socket
時,預設的連結超時時間為0(A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.),也就意味著連結永不超時,直到發生連結超時異常,所以程式會被卡住,並最終丟擲異常。
二、正確示例
若要設定連結超時,需要使用如下方式建立Socket
:
Socket s = new Socket();
SocketAddress socketAddress = new InetSocketAddress(serverIp, port);
s.connect(socketAddress, timeout);
其中timeout
就是設定的超時時間,當超時時間到時會丟擲SocketTimeoutException
而不會無限等待的去嘗試連結。
附
設定從Socket讀取資料超時
通過Socket
方法setSoTimeout(int timeout)
,Javadoc關於該方法的的說明如下:
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.