class RubyWolf::Connection

Attributes

body[R]
headers[R]
method[R]
path[R]
query[R]
read_chunk[R]
socket[R]
write_chunk[R]

Public Class Methods

new(socket) click to toggle source
# File lib/ruby_wolf/connection.rb, line 5
def initialize(socket)
  @socket = socket
  @read_chunk = ''
  @write_chunk = ''
  @reading = true

  @headers = {}
end

Public Instance Methods

close() click to toggle source
# File lib/ruby_wolf/connection.rb, line 46
def close
  @socket.close
end
enqueue_write(data) click to toggle source
# File lib/ruby_wolf/connection.rb, line 29
def enqueue_write(data)
  @write_chunk += data
end
need_to_read?() click to toggle source
# File lib/ruby_wolf/connection.rb, line 14
def need_to_read?
  @reading
end
need_to_write?() click to toggle source
# File lib/ruby_wolf/connection.rb, line 38
def need_to_write?
  !@write_chunk.bytesize.zero?
end
read() click to toggle source
# File lib/ruby_wolf/connection.rb, line 18
def read
  @read_chunk << socket.read_nonblock(RubyWolf::READ_SIZE)
  if @content_length.nil?
    read_headers
  else
    read_body
  end
rescue EOFError
  @reading = false
end
to_io() click to toggle source
# File lib/ruby_wolf/connection.rb, line 42
def to_io
  @socket
end
write() click to toggle source
# File lib/ruby_wolf/connection.rb, line 33
def write
  writen = socket.write_nonblock(@write_chunk)
  @write_chunk = @write_chunk.byteslice(writen, @write_chunk.bytesize)
end

Private Instance Methods

parse_headers(headers_chunk) click to toggle source
# File lib/ruby_wolf/connection.rb, line 64
def parse_headers(headers_chunk)
  parser = Http::Parser.new
  parser.on_headers_complete = proc do
    @headers = parser.headers
    @method = parser.http_method
    uri = URI.parse(parser.request_url)
    @path = uri.path
    @query = uri.query
    :stop
  end
  parser << headers_chunk
end
read_body() click to toggle source
# File lib/ruby_wolf/connection.rb, line 77
def read_body
  @reading = false if @read_chunk.bytesize >= @content_length
end
read_headers() click to toggle source
# File lib/ruby_wolf/connection.rb, line 52
def read_headers
  header_ending = @read_chunk.index(RubyWolf::HEADER_ENDING)
  return if header_ending.nil?

  headers_chunk = @read_chunk.slice!(
    0, header_ending + RubyWolf::HEADER_ENDING.size
  )
  parse_headers(headers_chunk)
  @content_length = @headers['Content-Length'].to_i
  read_body
end