Ruby gem&#t; tcp_timeout'未能抑制提出错误

时间:2015-09-28 14:48:58

标签: ruby

我使用' socket'编写了一个脚本。连接到主机和端口,因为socket.timeout没有真正起作用,我尝试使用' tcp_timeout'宝石工作正常,但我似乎无法抑制连接/读/写超时发生时引发的错误。知道我哪里错了吗?

begin
  socket = TCPTimeout::TCPSocket.new(server, port, connect_timeout: 6, read_timeout: 6)
  unless socket.read(12) =~ /^SMTH\n$/
    puts "[!] #{server} banner error"
    exit(1)
  end
rescue TCPTimeout::SocketTimeout => err
  puts "[!] #{server} Timeout"
  exit(1)
end

引发的错误,正如预期的那样是读取超时错误:

/usr/local/rvm/gems/ruby-1.9.3-p551/gems/tcp_timeout-0.1.1/lib/tcp_timeout.rb:160:in `select_timeout': read timeout (TCPTimeout::SocketTimeout)
        from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/tcp_timeout-0.1.1/lib/tcp_timeout.rb:108:in `block in read'
        from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/tcp_timeout-0.1.1/lib/tcp_timeout.rb:107:in `loop'
        from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/tcp_timeout-0.1.1/lib/tcp_timeout.rb:107:in `read'
        from ./myhost.rb:67:in `<main>'

我甚至尝试过:

rescue TCPTimeout::SocketTimeout, StandardError, Timeout::Error => err

同样的事情发生了。

1 个答案:

答案 0 :(得分:1)

tcp_timeout的作者在这里;你的代码看起来正确。这个片段按预期工作(对我来说):

require 'tcp_timeout'
begin
  socket = TCPTimeout::TCPSocket.new('stackoverflow.com', 80, read_timeout: 1)
  socket.read(100)
rescue TCPTimeout::SocketTimeout => e
  puts 'Rescued!', e
end

如果您能找到可靠地针对公共服务器的代码段,请提交错误:https://github.com/lann/tcp-timeout-ruby/issues