使用 Timeout::timeout(n) 缩短套接字超时似乎对我不起作用 [英] Shortening socket timeout using Timeout::timeout(n) does not seem to work for me
问题描述
我在 https://stackoverflow.com/questions/517219?tab=oldest#tab-top 但是,它对我不起作用.
I found what I thought should work perfectly at https://stackoverflow.com/questions/517219?tab=oldest#tab-top but, it did not work for me.
我在 Windows 上安装了 Ruby 1.9.1,当我尝试示例is_port_open"测试时,它不起作用.无论我为超时设置什么值,套接字调用仍然需要大约 20 秒才能超时.任何想法为什么?
I have Ruby 1.9.1 installed on Windows and, when I try the example "is_port_open" test, it does not work. The socket call still takes around 20 seconds to timeout no matter what value I set for the timeout. Any ideas why?
推荐答案
以下代码似乎适用于 Windows 上的 ruby 1.9.1:
The following code seems to work with ruby 1.9.1 on Windows:
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 上运行(它可以在其他操作系统上运行).
I haven't figured out yet why the original is_port_open?() code doesn't work on Windows with ruby 1.9.1 (it works on other OSes).
这篇关于使用 Timeout::timeout(n) 缩短套接字超时似乎对我不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!