java - 如何捕获 SocketTimeoutException

标签 java

假设我有一个名为 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() 的两个参数版本,其中您提供超时。

关于java - 如何捕获 SocketTimeoutException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13736899/

相关文章:

java - @Value 用于在 Spring 3 中初始化 java.util.Date

java - 在 ListView 中选择一行

java - Akka 消息和参与者的命名约定

java - JERSEY : Error Trace : java. lang.IllegalStateException: 实体输入流已经关闭

java - Spring AMQP——@RabbitListener 是在幕后轮询吗?

java - 如何洗牌对

java - startDrag 方法已弃用,无法编译程序

java - Spring MVC 3.0-传递模型和 View 对象时,URL 映射被视为 View

java - 我对 : how Eclipse MAT displays "Unreachable" objects. 有点困惑我正在阅读两个客户转储并想跟踪无法访问的对象

java - 构造函数注入(inject)阻止自定义资源处理