Class: Async::HTTP::Server

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

Instance Method Summary collapse

Constructor Details

#initialize(endpoint, protocol_class = Protocol::HTTP1, &block) ⇒ Server

Returns a new instance of Server.



28
29
30
31
32
33
34
35
# File 'lib/async/http/server.rb', line 28

def initialize(endpoint, protocol_class = Protocol::HTTP1, &block)
  @endpoint = endpoint
  @protocol_class = protocol_class || endpoint.protocol
  
  if block_given?
    self.define_singleton_method(:handle_request, block)
  end
end

Instance Method Details

#accept(peer, address, task: Task.current) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/async/http/server.rb', line 41

def accept(peer, address, task: Task.current)
  stream = Async::IO::Stream.new(peer)
  protocol = @protocol_class.server(stream)
  
  # Async.logger.debug(self) {"Incoming connnection from #{address.inspect}"}
  
  hijack = catch(:hijack) do
    protocol.receive_requests do |request|
      # Async.logger.debug(self) {"Incoming request from #{address.inspect}: #{request.method} #{request.path}"}
      handle_request(request, peer, address)
    end
  end
  
  if hijack
    hijack.call(peer)
  end
rescue EOFError, Errno::ECONNRESET, Errno::EPIPE
  # Sometimes client will disconnect without completing a result or reading the entire buffer.
  return nil
ensure
  peer.close
end

#handle_request(request, peer, address) ⇒ Object



37
38
39
# File 'lib/async/http/server.rb', line 37

def handle_request(request, peer, address)
  [200, {"Content-Type" => "text/plain"}, ["Hello World"]]
end

#runObject



64
65
66
# File 'lib/async/http/server.rb', line 64

def run
  @endpoint.accept(&self.method(:accept))
end