假设我有一个名为SuperSocket的套接字变量,有什么办法可以捕获超时异常吗?
SuperSocket.setSoTimeout(5000);
catch (SocketTimeoutException e){
System.out.println("Timeout");
System.exit(1);
}
来自Javadoc:(http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html)
public void setSoTimeout(int timeout)
throws SocketExceptionEnable/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.
SocketTimeoutException被抛出(然后被捕获)的唯一时间是在Socket的底层InputStream上执行阻塞读取并且在指定时间内没有接收到数据(导致读取…超时).
superSocket.setSoTimeout(5000);
InputStream is = superSocket.getInputStream();
int i;
try {
i = is.read();
} catch (SocketTimeoutException ste) {
System.out.println("I timed out!");
}