0

I want to check for a connection to a specific server with Ruby. So I just wrap the HTTP request into a begin/rescue construct and try again in a few seconds if the connection is not available.

Problem: If I start the program with no connection available (link down) it will never succeed in finding a connection even if at some time the connection is available (e.g. via ping, browser request).

Code:

require 'net/http'

loop do 

    begin
        uri = URI.parse 'http://www.example.com'
        resp = Net::HTTP.get uri
    rescue SocketError => se
        puts se
        sleep 3
        next
    rescue Exception => e
        puts e
        break   
    end

    puts 'It works!'
    break

end

Steps to reproduce:

  1. Take network link down
  2. Start program
  3. -> getaddrinfo: Name or service not known
  4. -> ...
  5. Turn network link on again
  6. Still no connection, same error

Why is that?

Ruby version: ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux]

4

0 回答 0