Does Ruby "open_uri" really close sockets reliably after reading or crashing?

I used open_urito pull the ftp path as a data source for some time, but unexpectedly found that I was almost constantly "530 Sorry, the maximum number of allowed clients (95) is already connected."

I am not sure if my code is defective, or if it is someone else who is accessing the server, and, unfortunately, it does not seem to me that I really know exactly who is to blame.

Essentially, I am reading FTP-URI with:

  def self.read_uri(uri)
    begin
      uri = open(uri).read
      uri == "Error" ? nil : uri
    rescue OpenURI::HTTPError
      nil
    end
  end

I assume that I need to add additional error handling code here ... I want to be sure that I take all precautions to close all connections so that my connections are not a problem, however I thought open_uri + read would take this measure precautions against using Net :: FTP methods.

The bottom line is that I must be 100% sure that these connections are closed, and I do not have any connections with open connections.

Can anyone advise using read_uri correctly to load ftp with a guarantee to close the connection? Or should I shift the logic to Net :: FTP, which can lead to more control over the situation if open_uri is not reliable enough?

Net:: FTP, , vs, tmp, ( fs, )?

+5
2

, . OpenURI docs :

It is possible to open http/https/ftp URL as usual like opening a file:

open("http://www.ruby-lang.org/") {|f|
  f.each_line {|line| p line}
}

, open_uri , , , , :

uri = ''
open("http://www.ruby-lang.org/") {|f|
  uri = f.read
}

, .


:

# The list of URLs to pass in to check if one times out or is refused.
urls = %w[
  http://www.ruby-lang.org/
  http://www2.ruby-lang.org/
]

# the method
def self.read_uri(urls)

  content = ''

  open(urls.shift) { |f| content = f.read }
  content == "Error" ? nil : content

  rescue OpenURI::HTTPError
    retry if (urls.any?)
    nil
end
+6

:

data = open(uri){|f| f.read}
+4

All Articles