Net::HTTP timeouts not respected depending on how it's used?

In my Mac with Leopard, this doesn't respect the 2 seconds timeout
that's set in the code...

require 'net/http'
require 'uri'

url = URI.parse("http://222.222.3.234")
req = Net::HTTP::Get.new(url.request_uri)
res = Net::HTTP.start(url.host, url.port) { |http|
  http.open_timeout = 2
  http.read_timeout = 2
  http.request(req)
}
puts res.body

It times out, but after 1 MINUTE, with this message...
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:564:in
`initialize': Operation timed out - connect(2) (Errno::ETIMEDOUT)

However, the following code works (i.e. it times out after the 2
seconds)...

require 'net/http'

site = Net::HTTP.new("http://222.222.3.234")
site.open_timeout = 2
site.read_timeout = 2
res = site.get2(URI.escape("/"))
puts res.body

After the 2 seconds I get this message
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/timeout.rb:54:in
`open': execution expired (Timeout::Error)

Do you know why the timeout is not respected in the first case? (I don't
understand)

Thanks in advance.

Xavi

···

--
Posted via http://www.ruby-forum.com/.

Ei Xavi!

I've traced the code:

   Class method start instantiates a new http object
   and invokes start on it

   Instance method start calls do_start, which in turn
   invokes connect, and *then* yields

So by the time the block is executed the connection has already been attempted with default (nil) open timeout value.

With the current implementation you can't tweak the open timeout and use the block form, you need to go with the alternative you already know it works.

-- fxn

···

On Apr 8, 2008, at 21:42 , Xavi Caballe wrote:

In my Mac with Leopard, this doesn't respect the 2 seconds timeout
that's set in the code...

require 'net/http'
require 'uri'

url = URI.parse("http://222.222.3.234")
req = Net::HTTP::Get.new(url.request_uri)
res = Net::HTTP.start(url.host, url.port) { |http|
http.open_timeout = 2
http.read_timeout = 2
http.request(req)
}
puts res.body

It times out, but after 1 MINUTE, with this message...
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:564:in
`initialize': Operation timed out - connect(2) (Errno::ETIMEDOUT)