Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env ruby
- #encoding utf-8
- $LOAD_PATH<<"."
- require 'getoptlong'
- require 'io/console'
- require 'socket'
- def quit_server
- puts "Hit 'q' to shutdown and exit server"
- loop do
- char = STDIN.getch
- if char == 'q'
- puts "Shutting down server... Exiting"
- exit(0)
- end
- end
- end
- def box_string(str)
- line = "|--"+'-' * str.length+"--|"
- puts line
- puts "|->"+str+"<-|"
- puts line
- end
- def check_commandline
- GetoptLong.new(
- ['--Port', '--P', GetoptLong::REQUIRED_ARGUMENT],
- ['--Addr', '--A', GetoptLong::REQUIRED_ARGUMENT]
- ).yield_self(
- &->(g){
- port = nil
- addr = nil
- g.each{
- |o, a|
- case o
- when '--Port' || '--P'
- begin
- port = Integer(a)
- rescue
- puts("Port must be a integer: #{a}")
- exit(1)
- end
- when '--Addr' || '--A'
- addr = a.to_s
- end
- }
- [port, addr]
- }
- )
- 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(n/y)? "
- 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})")
- Thread.new{ quit_server }
- loop do
- client = server.accept
- client<<"Here's the current time: "<<(Time.now.ctime)<<"\n"
- client.close
- end
- server.close
- end
Add Comment
Please, Sign In to add comment