簡體   English   中英

在從給定IP范圍向IP發送請求並跳過具有超時的IP並轉移到下一個IP時,如何在ruby中使用net / http處理超時?

[英]How to handle timeout with net/http in ruby while sending requests to IPs from given IP range and skip IPs with timeout and move to next ones?

我想處理從控制台發出的IP范圍的超時,對此控制台向請求的IP范圍內的IP發出請求並收到超時錯誤。 我想向所有IP提出請求並從中獲得響應。 對於超時的IP,要跳過它並移至下一個。 如何處理此循環,不會出現異常,腳本會將請求發送到所有IP,這些IP可以使響應處理超時。

在此處附加代碼:

require 'net/http'
require 'uri'
require 'ipaddr'

puts "Origin IP:"
originip = gets()
(IPAddr.new("209.85.175.121")..IPAddr.new("209.85.175.150")).each do |address|
  req = Net::HTTP.get(URI.parse("http://#{address.to_s}"))
  puts req
end

錯誤:

C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `initialize': A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. - connect(2) (Errno::ETIMEDOUT)
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `open'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `connect'
        from C:/Ruby187/lib/ruby/1.8/timeout.rb:53:in `timeout'
        from C:/Ruby187/lib/ruby/1.8/timeout.rb:101:in `timeout'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:560:in `connect'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:553:in `do_start'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:542:in `start'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:379:in `get_response'
        from C:/Ruby187/lib/ruby/1.8/net/http.rb:356:in `get'
        from IP Range 2.rb:9
        from IP Range 2.rb:8:in `each'

就像馬克說的那樣。 您應該挽救異常。 像這樣:

begin
  response = Net::HTTP.get(...)
rescue Errno::ECONNREFUSED => e
  # Do what you think needs to be done
end

同樣,從對get()的調用中獲得的回報是響應,而不是請求。

使用timeout捕獲異常,

require 'timeout'

(IPAddr.new("209.85.175.121")..IPAddr.new("209.85.175.150")).each do |address|
  begin
    req = Net::HTTP.get(URI.parse("http://#{address.to_s}"))
    puts req
  rescue Timeout::Error => exc
    puts "ERROR: #{exc.message}"
  rescue Errno::ETIMEDOUT => exc
    puts "ERROR: #{exc.message}"
  # uncomment the following two lines, if you are not able to track the exception type.
  #rescue Exception => exc
  #  puts "ERROR: #{exc.message}"
  end
end

編輯:當我們營救Timeout::Error ,只會捕獲屬於Timeout::Error類的那些異常。 我們需要使用他們的錯誤類捕獲引發的異常,並相應地更新代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM