From 5a30febc653b04a5c9cf2ebda60f5d05ce11c4ed Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sun, 17 Jun 2012 09:11:43 -0400 Subject: [PATCH] practicing a bit with optparse --- ruby-sockets/marco-polo/client.rb | 55 ++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/ruby-sockets/marco-polo/client.rb b/ruby-sockets/marco-polo/client.rb index 4560269..52d32ca 100644 --- a/ruby-sockets/marco-polo/client.rb +++ b/ruby-sockets/marco-polo/client.rb @@ -1,23 +1,60 @@ +require 'optparse' 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" +def main(args = ARGV) + options = { + :type => :write, + :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 backoff = 0.5 nextloc = [rand(0..99), rand(0..99)] loop do begin - TCPSocket.open('127.0.0.1', 22000) do |sock| + TCPSocket.open('127.0.0.1', port) do |sock| case client_type - when 'read' - sock.send("marco sally\n", 0) + when :read + sock.send("marco #{client_name}\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) + when :write + sock.send("polo #{client_name} #{nextloc.first} #{nextloc.last}\n", 0) nextloc = sock.recv(100).to_s.split.map(&:to_i) puts "sent location '#{nextloc.first} #{nextloc.last}'" end