使用Timeout :: timeout(n)缩短套接字超时对我来说似乎不起作用

chr*_*gle 2 ruby sockets connection-timeout

我在/sf/ask/36205361/?tab=oldest#tab-top找到了我认为应该完美的工作但是,它对我不起作用.

我在Windows上安装了Ruby 1.9.1,当我尝试"is_port_open"测试时,它不起作用.无论我为超时设置什么值,套接字调用仍然需要大约20秒才能超时.有什么想法吗?

joa*_*ast 5

以下代码似乎适用于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
Run Code Online (Sandbox Code Playgroud)

我还没弄清楚为什么原来的is_port_open?()代码在带有ruby 1.9.1的Windows上不起作用(它适用于其他操作系统).