Class: Server::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/server/server.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dispatcher) ⇒ Server

Returns a new instance of Server.



8
9
10
# File 'lib/server/server.rb', line 8

def initialize(dispatcher)
  @dispatcher = dispatcher
end

Class Method Details

.log(msg) ⇒ Object



40
41
42
# File 'lib/server/server.rb', line 40

def self.log msg
  STDERR.puts msg
end

Instance Method Details

#listen(port, host) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/server/server.rb', line 12

def listen(port, host)
  server = TCPServer.new(host, port)
  Server.log "Server bound to http://#{host}:#{port}"

  loop do
    socket       = server.accept
    request      = Request.new socket
    response     = Response.new request

    next if request.empty?
    Server.log request.inspect

    begin
      @dispatcher.dispatch(request, response)
    rescue Exception => e
      msg = "#{e.backtrace.first}: #{e.message} (#{e.class})", e.backtrace.drop(1).map{|s| "\t#{s}"}
      Server.log msg
      socket.print "HTTP/1.1 200 OK\r\nContent-Type: text/html;charset=utf-8\r\n\r\n"
      socket.print '<html><body><pre style="max-width: 100%; color: red; width: 100%; font-size:20px; white-space: normal;">'

      socket.print msg.join("<br>")
      socket.print '</pre></body></html>'
    end

    socket.close
  end
end