Skip to content

Commit

Permalink
Wait for the DRb server to be ready instead of waiting an arbitrary s…
Browse files Browse the repository at this point in the history
…econd.
  • Loading branch information
threedaymonk committed Oct 2, 2011
1 parent 7185777 commit 58ff7fc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion bin/play.rb
@@ -1,6 +1,7 @@
$:.unshift File.expand_path("../../lib", __FILE__)
require "battleship/game"
require "battleship/console_renderer"
require "battleship/util"
require "stringio"
require "digest/sha1"
require "forwardable"
Expand Down Expand Up @@ -39,8 +40,8 @@ def kill
port = PORT + i
secret = Digest::SHA1.hexdigest("#{Time.now}#{rand}#{i}")
system %{ruby #{player_server} "#{path}" #{port} #{secret} &}
Battleship::Util.wait_for_socket("localhost", port)
players << PlayerClient.new(secret, DRbObject.new(nil, "druby://localhost:#{port}"))
sleep 1
end

winners = []
Expand Down
20 changes: 20 additions & 0 deletions lib/battleship/util.rb
@@ -1,3 +1,5 @@
require "socket"

module Battleship
module Util
PLAYER_METHODS = [:name, :new_game, :take_turn]
Expand All @@ -10,5 +12,23 @@ def find_player_classes
(klass.instance_methods & PLAYER_METHODS) == PLAYER_METHODS
}
end

def wait_for_socket(host, port, timeout=1)
socket = Socket.new(:INET, :STREAM)
address = Socket.pack_sockaddr_in(port, host)
optval = [timeout, 0].pack("l_2")
socket.setsockopt :SOCKET, :RCVTIMEO, optval
socket.setsockopt :SOCKET, :SNDTIMEO, optval

loop do
begin
socket.connect(address)
return
rescue SystemCallError => e
end
end
end

extend self
end
end

0 comments on commit 58ff7fc

Please sign in to comment.