java – 如何捕获SocketTimeoutException

前端之家收集整理的这篇文章主要介绍了java – 如何捕获SocketTimeoutException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

假设我有一个名为SuperSocket的套接字变量,有什么办法可以捕获超时异常吗?

       SuperSocket.setSoTimeout(5000);

       catch (SocketTimeoutException e){
        System.out.println("Timeout");
        System.exit(1);
    }
最佳答案
您似乎无法理解setSoTimeout()的作用以及何时抛出该异常.

来自Javadoc:(http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html)

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()的两个参数版本,那么您将提供超时.

原文链接:https://www.f2er.com/java/438262.html

猜你在找的Java相关文章