saltycracker

SimpleTCPWithThreadToShutDown

Jun 8th, 2020
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.64 KB | None | 0 0
  1. #! /usr/bin/env ruby
  2. #encoding utf-8
  3.  
  4. $LOAD_PATH<<"."
  5.  
  6. require 'getoptlong'
  7. require 'io/console'
  8. require 'socket'
  9.  
  10. def quit_server
  11.   puts "Hit 'q' to shutdown and exit server"
  12.   loop do
  13.     char = STDIN.getch
  14.     if char == 'q'
  15.       puts "Shutting down server... Exiting"
  16.       exit(0)
  17.     end
  18.   end
  19. end
  20.  
  21. def box_string(str)
  22.   line = "|--"+'-' * str.length+"--|"
  23.   puts line
  24.   puts "|->"+str+"<-|"
  25.   puts line
  26. end
  27.  
  28. def check_commandline
  29.  
  30.   GetoptLong.new(
  31.     ['--Port', '--P', GetoptLong::REQUIRED_ARGUMENT],
  32.     ['--Addr', '--A', GetoptLong::REQUIRED_ARGUMENT]
  33.   ).yield_self(
  34.     &->(g){
  35.       port = nil
  36.       addr = nil
  37.       g.each{
  38.         |o, a|
  39.         case o
  40.         when '--Port' || '--P'
  41.           begin
  42.             port = Integer(a)
  43.           rescue
  44.             puts("Port must be a integer: #{a}")
  45.             exit(1)
  46.           end
  47.         when '--Addr' || '--A'
  48.           addr = a.to_s
  49.         end
  50.       }
  51.       [port, addr]
  52.     }
  53.   )
  54.  
  55. end
  56.  
  57. if __FILE__ == $0
  58.  
  59.   port, addr = check_commandline
  60.    
  61.   if port.nil? || addr.nil?
  62.     puts "Must call #{$PROGRAM_NAME} with --Port|P=1234 --Addr|A=127.0.0.1"
  63.     exit(1)
  64.   end
  65.  
  66.   box_string("Server on: #{addr}:(#{port})")
  67.  
  68.   print "Start server(n/y)? "
  69.   STDOUT.flush
  70.  
  71.   unless gets.chomp =~ /^y$/
  72.     puts "Exiting #{$PROGRAM_NAME}"
  73.     exit(0)
  74.   end
  75.  
  76.   server = TCPServer.new(addr, port)
  77.  
  78.   box_string("Server active on: #{addr}:(#{port})")
  79.  
  80.   Thread.new{ quit_server }
  81.  
  82.   loop do
  83.     client = server.accept
  84.     client<<"Here's the current time: "<<(Time.now.ctime)<<"\n"
  85.     client.close
  86.   end
  87.  
  88.   server.close
  89.  
  90. end
Add Comment
Please, Sign In to add comment