加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何捕获SocketTimeoutException

发布时间:2020-12-14 19:22:59 所属栏目:Java 来源:网络整理
导读:假设我有一个名为SuperSocket的套接字变量,有什么办法可以捕获超时异常吗? SuperSocket.setSoTimeout(5000); catch (SocketTimeoutException e){ System.out.println("Timeout"); System.exit(1); } 最佳答案 您似乎无法理解setSoTimeout()的作用以及何时抛

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读