您似乎无法理解setSoTimeout()的作用以及何时抛出该异常.
public void setSoTimeout(int timeout)
throws SocketException
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.
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!");
}
编辑添加:实际上还有一次可以抛出异常,如果您正在调用Socket.connect()的两个参数版本,那么您将提供超时.