practicing a bit with optparse

This commit is contained in:
Dan Buch 2012-06-17 09:11:43 -04:00
parent 84fc0a2062
commit 5a30febc65

View File

@ -1,23 +1,60 @@
require 'optparse'
require 'socket' require 'socket'
def main def main(args = ARGV)
client_type = %w(read write).include?(ARGV.first) ? ARGV.first : 'read' options = {
sleep_interval = (ARGV[1] || 0).to_f :type => :write,
puts "Starting #{client_type} client" :sleep_interval => 1.0,
:name => 'sally',
:port => 22000
}
OptionParser.new do |opts|
opts.banner = "Usage: ruby #{File.basename($0)} [options]"
opts.on('-t [TYPE]', '--type [TYPE]', [:read, :write],
"Client type (read/write), default=#{options[:type].to_s}") do |t|
options[:type] = t
end
opts.on('-n [NAME]', '--name [NAME]',
"Client (player) name, default='#{options[:name]}'") do |n|
options[:name] = n
end
opts.on('-s [SLEEP_INTERVAL]', '--sleep [SLEEP_INTERVAL]',
"Sleep interval between requests, " <<
"default=#{options[:sleep_interval]}") do |s|
options[:sleep_interval] = s.to_f
end
opts.on('-p [PORT]', '--port [PORT]', Integer,
"Server port, default=#{options[:port]}") do |p|
options[:port] = p
end
end.parse!(args)
run_client(options)
end
def run_client(options)
client_type = options.fetch(:type, :read)
client_name = options.fetch(:name, 'sally')
sleep_interval = options.fetch(:sleep_interval, 1.0)
port = options.fetch(:port, 22000)
puts "Starting #{client_type} client for '#{client_name}', " <<
"interval=#{sleep_interval}, port=#{port}"
successes = 0 successes = 0
backoff = 0.5 backoff = 0.5
nextloc = [rand(0..99), rand(0..99)] nextloc = [rand(0..99), rand(0..99)]
loop do loop do
begin begin
TCPSocket.open('127.0.0.1', 22000) do |sock| TCPSocket.open('127.0.0.1', port) do |sock|
case client_type case client_type
when 'read' when :read
sock.send("marco sally\n", 0) sock.send("marco #{client_name}\n", 0)
location = sock.recv(100).to_s.split[2,4].map(&:to_i) location = sock.recv(100).to_s.split[2,4].map(&:to_i)
puts "#{location.first} #{location.last}" puts "#{location.first} #{location.last}"
when 'write' when :write
sock.send("polo sally #{nextloc.first} #{nextloc.last}\n", 0) sock.send("polo #{client_name} #{nextloc.first} #{nextloc.last}\n", 0)
nextloc = sock.recv(100).to_s.split.map(&:to_i) nextloc = sock.recv(100).to_s.split.map(&:to_i)
puts "sent location '#{nextloc.first} #{nextloc.last}'" puts "sent location '#{nextloc.first} #{nextloc.last}'"
end end