#! /usr/bin/env ruby #encoding utf-8 $LOAD_PATH<<"." require 'io/console' require 'socket' require 'getoptlong' def check_commandline GetoptLong.new( ['--Port', '--P', GetoptLong::OPTIONAL_ARGUMENT], ['--Addr', '--A', GetoptLong::OPTIONAL_ARGUMENT], ['--Help', '--H', GetoptLong::OPTIONAL_ARGUMENT] ).yield_self( &->(g){ port = nil addr = nil g.each { |o, a| case o when '--Port' || '--P' begin port = Integer(a) rescue puts "Port number must be an integer: (#{a})" exit(1) end when '--Addr' || '--A' addr = a when '--Help' || '--H' puts "Must call #{$PROGRAM_NAME} with --Port|P=1234 --Addr|A=127.0.0.1" exit(0) end } [port, addr] } ) end def box_string(str) line = "|--"+'-' * str.length+"--|" puts line puts "|->"+str+"<-|" puts line end def quit_server puts "Hit 'q' to shutdown server and exit" loop do char = STDIN.getch if char == 'q' puts "Shutting down server... Exiting..." exit(0) end end end if __FILE__ == $0 port, addr = check_commandline if port.nil? || addr.nil? puts("Must call #{$PROGRAM_NAME} with --Port|P=1234 --Addr|A=127.0.0.1") exit(1) end box_string("Server on: #{addr}:(#{port})") print "Start server(y/n)? " STDOUT.flush unless gets.chomp =~ /^y$/ puts "Exiting #{$PROGRAM_NAME}" exit(0) end server = TCPServer.new(addr, port) box_string("Server active on: #{addr}:(#{port})") puts "Server running..." Thread.new{ quit_server } loop do client = server.accept user = client.gets.chomp print "Message from #{user}\r\n" client<<"Here's the current date/time for #{user}: "<<(Time.now.ctime)<<"\n" client.close end server.close end ###---Client follows #! /usr/bin/env ruby #encoding utf-8 $LOAD_PATH<<"." require 'io/console' require 'socket' require 'getoptlong' def check_commandline GetoptLong.new( ['--Port', '--P', GetoptLong::OPTIONAL_ARGUMENT], ['--Addr', '--A', GetoptLong::OPTIONAL_ARGUMENT], ['--User', '--U', GetoptLong::OPTIONAL_ARGUMENT], ['--Help', '--H', GetoptLong::OPTIONAL_ARGUMENT] ).yield_self( &->(g){ port = nil addr = nil user = nil g.each { |o, a| case o when '--Port' || '--P' begin port = Integer(a) rescue puts "Port number must be an integer: (#{a})" exit(1) end when '--Addr' || '--A' addr = a when '--User' || '--U' user = a when '--Help' || '--H' puts "Must call #{$PROGRAM_NAME} with --Port|P=1234 --Addr|A=127.0.0.1 --User|U=UserName" exit(0) end } [port, addr, user] } ) end def box_string(str) line = "|--"+'-' * str.length+"--|" puts line puts "|->"+str+"<-|" puts line end if __FILE__ == $0 port, addr, user = check_commandline if port.nil? || addr.nil? || addr.nil? puts("Must call #{$PROGRAM_NAME} with --Port|P=1234 --Addr|A=127.0.0.1 --User|U=UserName") exit(1) end box_string("Client(#{user}) on: #{addr}:(#{port})") print "Start client(y/n)? " STDOUT.flush unless gets.chomp =~ /^y$/ puts "Exiting #{$PROGRAM_NAME}" exit(0) end begin client = TCPSocket.new(addr, port) box_string("Client(#{user}): #{addr}:(#{port})") client<