box-o-sand/ruby-sockets/marco-polo/client.rb

41 lines
1.0 KiB
Ruby

require 'socket'
def main
client_type = %w(read write).include?(ARGV.first) ? ARGV.first : 'read'
sleep_interval = (ARGV[1] || 0).to_f
puts "Starting #{client_type} client"
successes = 0
backoff = 0.5
nextloc = [rand(0..99), rand(0..99)]
loop do
begin
TCPSocket.open('127.0.0.1', 22000) do |sock|
case client_type
when 'read'
sock.send("marco sally\n", 0)
location = sock.recv(100).to_s.split[2,4].map(&:to_i)
puts "#{location.first} #{location.last}"
when 'write'
sock.send("polo sally #{nextloc.first} #{nextloc.last}\n", 0)
nextloc = sock.recv(100).to_s.split.map(&:to_i)
puts "sent location '#{nextloc.first} #{nextloc.last}'"
end
sock.close
end
successes += 1
backoff = 0.5
sleep sleep_interval
rescue
puts "made it #{successes} times. sleeping #{backoff} secs"
successes = 0
sleep backoff
backoff *= 2
end
end
end
if $0 == __FILE__
main
end