2014-09-27 112 views
0

即时通讯尝试连接的主机并不总是可用的,我有麻烦。 进出口使用的代码,其中IM连接到主机位:如何设置Net :: HTTP.start的超时时间?

begin #To catch error from Net::HTTP 
net = Net::HTTP.new(uri.host, uri.port) 
net.read_timeout = 5 
net.continue_timeout = 5 
res = net.start {|http| 
    http_request = http.request(req) 
    case http_request.response 
     case 
      ... 
     else 
      @error_msg = "Response not handled by appliaction" << http_request.code << " " << http_request.message 
    end 
} 
rescue SocketError => se 
    @error_msg = "Net::SocketError #{se} (Perhaps host is down?)" 
    puts @error_msg 
end 

问题是,当主机心不是响应(或别的东西是错误的)的连接似乎运行方式长。我所期待的5秒的等待, 但其试图对的方式来长:

Completed 500 Internal Server Error in 126302ms 
Errno::ETIMEDOUT - Connection timed out - connect(2): 

如何设置的最大超时为网:HTTP对象?

感谢

回答

0

由于Ascar指出的那样,这是错误的语法。 但是:单独的read_timeout并不能解决这个问题,我还需要添加:open_timeout,如果主机根本没有响应。

Net::HTTP.start(uri.host, uri.port, {read_timeout: 5, opentimeout: 5}) 
+0

不能与净:: SSH我得到'引发ArgumentError(无效选项(S):read_timeout,opentimeout)工作'红宝石2.3.3,净SSH(4.2.0,4.1.0,4.0 0.1) – 2018-02-27 18:10:00

2

你正在做什么是支持的方法达到ruby 1.8

对于ruby > 1.9你应该使用它作为启动选项。

试试这个:

res = net.start(:read_timeout => 5) { |http| # your block } 

Net:HTTP.start