Class: Server::Server

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

Instance Method Summary (collapse)

Constructor Details

- (Server) initialize(dispatcher)

Returns a new instance of Server



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

def initialize(dispatcher)
  @dispatcher = dispatcher
end

Instance Method Details

- (Object) listen(port, host)



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
# File 'lib/server/server.rb', line 12

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

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

    log request
    next if request.empty?

    begin
      @dispatcher.dispatch(request, response, self)
    rescue Exception => e
      msg = "#{e.backtrace.first}: #{e.message} (#{e.class})", e.backtrace.drop(1).map{|s| "\t#{s}"}
      log msg
      socket.print '<pre style="max-width: 100%; color: red; width: 100%; font-size:20px; white-space: normal;">'
      socket.print msg
      socket.print '</pre>'
    end

    socket.close
  end
end

- (Object) log(msg)



38
39
40
# File 'lib/server/server.rb', line 38

def log msg
  STDERR.puts msg
end