Java 套接字在断开连接时不会超时

标签 java linux sockets timeout xmpp

我在自动化测试中发现了一些奇怪的问题。

有以下设置: 服务器: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/

相关文章:

php - 优化 Nginx + PHP-FPM 500 万日浏览量

PHP 5.3.29 版亚马逊 Linux 上的 PHP imagemagick 设置问题

c - 为什么长时间运行的程序总是要收割它们的僵尸 child ?

Python 原始套接字 - IP_HDRINCL 选项

java - 在 android 上使用 Socket.IO 总是返回 XHR 轮询错误

java - Activity.getIntent() 可以返回 null 吗?

java - 我如何在我的其他东西(Android)中使用 WebView 中的 session ?

java - 按 T​​ab 键时 Silk4J 对象映射编辑器中出现 NullPointerException

java - Google Analytics 已弃用登录

c# - C#原始套接字接收数据包