【问题标题】:Shortening socket timeout using Timeout::timeout(n) does not seem to work for me使用 Timeout::timeout(n) 缩短套接字超时似乎对我不起作用
【发布时间】:2010-08-12 03:29:28
【问题描述】:
【问题讨论】:
标签:
ruby
sockets
connection-timeout
【解决方案1】:
以下代码似乎适用于 Windows 上的 ruby 1.9.1:
require 'socket'
def is_port_open?(ip, port)
s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
sa = Socket.sockaddr_in(port, ip)
begin
s.connect_nonblock(sa)
rescue Errno::EINPROGRESS
if IO.select(nil, [s], nil, 1)
begin
s.connect_nonblock(sa)
rescue Errno::EISCONN
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
end
return false
end
我还没弄清楚为什么原来的 is_port_open?() 代码不能在 ruby 1.9.1 的 Windows 上工作(它在其他操作系统上工作)。
【解决方案2】:
这可能是由于 Rubys Timeout 库的一些固有问题。您可以通过直接访问底层套接字库并在 Socket 上设置超时来实现此目的。 article 对此进行了一些深入的介绍,尽管它假设 *nix,因此您可能对 Windows 有一些问题,我不确定套接字实现有多相似。