Class: Didao
- Inherits:
-
Object
- Object
- Didao
- Defined in:
- lib/didao.rb
Overview
A class representing a single gopher server instance
Instance Method Summary collapse
- #handle_request(request, source) ⇒ Object
-
#initialize(port = 70, path = Dir.pwd) ⇒ Didao
constructor
A new instance of Didao.
- #process_file(file_name) ⇒ Object
- #run ⇒ Object
Constructor Details
#initialize(port = 70, path = Dir.pwd) ⇒ Didao
Returns a new instance of Didao.
7 8 9 10 11 12 |
# File 'lib/didao.rb', line 7 def initialize(port = 70, path = Dir.pwd) @port = port @path = path @path += '/' unless @path =~ %r{\/$} @server = TCPServer.open(port) end |
Instance Method Details
#handle_request(request, source) ⇒ Object
25 26 27 28 29 30 31 32 |
# File 'lib/didao.rb', line 25 def handle_request(request, source) gopher_path = request.gsub("\r\n", '<CR><LF>') puts '---' puts "#{Time.now}: Received request: \"#{gopher_path}\" from #{source}" file = request == "\r\n" ? 'gophermap' : request.chomp puts "#{Time.now}: Returning requested file: \"#{file}\"" process_file(file) end |
#process_file(file_name) ⇒ Object
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/didao.rb', line 14 def process_file(file_name) file_name = file_name.sub(%r{^\/.\/}, '') File.open(@path + file_name, 'rb').read # This is technically nonstandard, as gophermaps should always end with '.' # This is best remedied outside this file, which should just be basic # server operations. rescue Errno::ENOENT => e puts e. 'Not Found' end |
#run ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/didao.rb', line 34 def run puts "Didao listening on #{@port}. Press Ctrl+C to exit." loop do client = @server.accept Thread.start(client) do |conn| conn.puts handle_request(conn.readline, conn.peeraddr[3]) conn.close end end rescue Interrupt puts "\nClosing Didao Server..." end |