2014-09-27 102 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