gpt4 book ai didi

java - 如何捕获 SocketTimeoutException

转载 作者:搜寻专家 更新时间:2023-10-31 20:13:44 25 4
gpt4 key购买 nike

假设我有一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com