Timeserver with optparse

#! /usr/bin/env ruby

# vi:set nu ai ap aw smd showmatch tabstop=4 shiftwidth=4:

# Name: ts.rb

require 'optparse'

require 'gserver'

# This hash will hold all of the options

# parsed from the command-line by

# OptionParser.

options = {}

# loop thru options

optparse = OptionParser.new do|opts|

# parse for port number

options[:port] = nil

opts.on( '-p', '--port PORT', 'Specify port' ) do |port|

options[:port] = port

end

# parse for listen address

options[:listen] = nil

opts.on( '-l', '--listen ADDRESS', 'Specify Interface' ) do |listen|

options[:listen] = listen

end

# display help

opts.on( '-h', '--help', 'Display this screen' ) do

puts opts

exit

end

end

# parse the options

optparse.parse!

# trap ctrl C

Kernel.trap('INT') { Kernel.exit }

#

# A server that returns the time in seconds since 1970.

#

class TimeServer < GServer

def initialize(port,host, *args)

super(port, host, *args)

end

def serve(io)

io.puts(Time.now.to_i)

end

end

# set defaults

options[:port] ||= 10001

options[:listen] ||= Socket.gethostname

# Run the server with logging enabled (it's a separate thread).

server = TimeServer.new(options[:port],options[:listen])

server.audit = true # Turn logging on.

# start it up

server.start

# and loop

server.join