Class: HTTPServer

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

Overview

Main class for managing and talking between sub-classes during request-response cycles. Utalizes the request, route and response classes.

Instance Method Summary collapse

Constructor Details

#initialize(port, router) ⇒ HTTPServer

Initializes the HTTPServer object

Parameters:

  • port (Int)

    An integer representing the port number for the http server

  • router (Router)

    The Router class holding the expected routes for the server



13
14
15
16
# File 'lib/tcp_server.rb', line 13

def initialize(port, router)
    @port = port
    @router = router
end

Instance Method Details

#startObject

Starts the TCP server and begins reading for requests on the designated port. When a request comes in it turns it into a request object using the request class, and sends that to the router. It then sends the matched information to the response class.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/tcp_server.rb', line 19

def start
    server = TCPServer.new(@port)
    puts "Listening on #{@port}"

    while session = server.accept
        data = ""
        while line = session.gets and line !~ /^\s*$/
            data += line
        end
        puts "RECEIVED REQUEST"
        puts "-" * 40
        puts data
        puts "-" * 40 

        request = Request.new(data)
        pp request
        
        routeReturn = @router.match_route(request)
        
        response = Response.new(routeReturn)
        response.print(session)
    end
end