Created
August 15, 2012 16:10
-
-
Save johnbintz/3361286 to your computer and use it in GitHub Desktop.
wait_for_port, a simple way to wait for a port to be open/closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Gem::Specification.new do |s| | |
s.name = 'wait_for_port' | |
s.version = '0.1.0' | |
s.platform = Gem::Platform::RUBY | |
s.author = 'John Bintz' | |
s.email = '[email protected]' | |
s.summary = 'Wait for a port to be open or not open.' | |
s.description = 'Wait for a port to be open or not open.' | |
s.files = ['wait_for_port.rb'] | |
s.require_path = '.' | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
module WaitForPort | |
def open?(*args) | |
wait_for_port(*args) | |
true | |
rescue => e | |
false | |
end | |
def closed?(*args) | |
wait_for_not_port(*args) | |
true | |
rescue => e | |
false | |
end | |
def wait_for_port(port, host = '127.0.0.1', timeout = 5) | |
if block_given? | |
return if open?(port, host, 1) | |
yield | |
end | |
begin | |
connected = false | |
begin | |
TCPSocket.new(host, port) | |
connected = true | |
rescue => e | |
timeout -= 1 | |
raise e if timeout == 0 | |
sleep 1 | |
end | |
end while !connected | |
end | |
def wait_for_not_port(port, host = '127.0.0.1', timeout = 5) | |
if block_given? | |
return if closed?(port, host, 1) | |
yield | |
end | |
begin | |
down = false | |
begin | |
TCPSocket.new(host, port) | |
timeout -= 1 | |
raise StandardError.new if timeout == 0 | |
sleep 1 | |
rescue => e | |
down = true | |
end | |
end while !down | |
end | |
extend self | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment