我在自动化测试中发现了一些奇怪的问题。
有以下设置: 服务器:Centos 6 客户端 1:Windows 7 客户端2:Centos 6
我正在编写测试,通过阻止服务器的 iptables
上的出站连接来模拟与服务器的连接中断。但是,套接字在 Windows 上的行为与在 Linux 客户端上的行为不同。
不过有一件事,在这两种情况下都有一行 Java 代码可以做到:
socket.setSoTimeout(0)
场景 #1(Windows):
- 发送
ssh
命令到服务器iptables -A OUTPUT --dport XYZ -j DROP
- 大约 60 秒后,我的控制台显示
java.net.SocketTimeoutException: Read timed out
- 连接断开
场景#2(Centos)
- 发送与上面相同的命令
- 我尝试等待多达 10 分钟,但控制台从不输出异常。
那么,问题,有没有办法让套接字的行为相同(或大致相同)?
我读到 Windows
实际上不使用 SO_TIMEOUT
而是使用 SO_RCVTIMEO
。
最佳答案
来自 setSoTimeout(int timeout) :
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.
你能设置一个实际的超时值吗?
关于Java 套接字在断开连接时不会超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25330071/