English 中文(简体)
Shortening socket timeout using Timeout::timeout(n) does not seem to work for me
原标题:

I found what I thought should work perfectly at https://stackoverflow.com/questions/517219?tab=oldest#tab-top but, it did not work for me.

I have Ruby 1.9.1 installed on Windows and, when I try the example "is_port_open" test, it does not work. The socket call still takes around 20 seconds to timeout no matter what value I set for the timeout. Any ideas why?

最佳回答

The following code seems to work with ruby 1.9.1 on Windows:

require  socket 

def is_port_open?(ip, port)
  s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
  sa = Socket.sockaddr_in(port, ip)

  begin
    s.connect_nonblock(sa)
  rescue Errno::EINPROGRESS
    if IO.select(nil, [s], nil, 1)
      begin
        s.connect_nonblock(sa)
      rescue Errno::EISCONN
        return true
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        return false
      end
    end
  end

  return false
end

I haven t figured out yet why the original is_port_open?() code doesn t work on Windows with ruby 1.9.1 (it works on other OSes).

问题回答

This may be due to some inherent problems with Rubys Timeout library. You can achieve this by directly accessing the underlying socket library and setting timeouts on the Socket. This article covers this in some depth, although it assumes *nix so you may have some issues with Windows, I m not sure how similar the socket implementations are.





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签