Class: Toycol::Server

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

Constant Summary collapse

BACKLOG =
1024
CHUNK_SIZE =
1024 * 16

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, **options) ⇒ Server

Returns a new instance of Server.



14
15
16
17
18
19
20
21
22
# File 'lib/toycol/server.rb', line 14

def initialize(app, **options)
  @app  = app
  @path = options[:Path]
  @port = options[:Port]
  @env  = default_env
  @returned_status  = nil
  @returned_headers = nil
  @returned_body    = nil
end

Class Method Details

.run(app, **options) ⇒ Object



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

def run(app, **options)
  new(app, **options).run
end

Instance Method Details

#runObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/toycol/server.rb', line 24

def run
  verify_file_path!
  server = UNIXServer.new @path
  server.listen BACKLOG

  loop do
    trap(:INT) { exit }

    socket = server.accept

    request_message = []
    request_message << socket.readpartial(CHUNK_SIZE) until socket.eof?
    request_message = request_message.join
    assign_parsed_attributes!(request_message)

    @returned_status, @returned_headers, @returned_body = @app.call(@env)

    socket.puts response_message
    socket.close_write
    socket.close
  end
end