Class: Proxi::HTTPConnection

Inherits:
Connection show all
Defined in:
lib/proxi/connection.rb

Instance Attribute Summary

Attributes inherited from Connection

#in_socket, #remote_host, #remote_port, #thread

Instance Method Summary collapse

Methods inherited from Connection

#alive?, #call, #join_thread

Constructor Details

#initialize(in_socket, host_to_ip) ⇒ HTTPConnection

Returns a new instance of HTTPConnection.



80
81
82
83
# File 'lib/proxi/connection.rb', line 80

def initialize(in_socket, host_to_ip)
  @in_socket, @host_to_ip = in_socket, host_to_ip
  @new = true
end

Instance Method Details

#handle_socket(socket) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/proxi/connection.rb', line 85

def handle_socket(socket)
  data = socket.readpartial(4096)

  if socket == in_socket
    broadcast(:data_in, self, data)

    if @new
      @first_packet = data
      @new = false
    end

    out_socket.write data
    out_socket.flush
  else
    broadcast(:data_out, self, data)
    in_socket.write data
    in_socket.flush
  end
end

#headersObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/proxi/connection.rb', line 120

def headers
  Hash[
    @first_packet
    .sub(/\r\n\r\n.*/m, '')
    .each_line
    .drop(1) # GET / HTTP/1.1
    .map do |line|
      k,v = line.split(':', 2)
      [k.downcase, v.strip].tap do |header|
        broadcast(:header, self, *header)
      end
    end
  ]
end

#out_socketObject



114
115
116
117
118
# File 'lib/proxi/connection.rb', line 114

def out_socket
  host, port = @host_to_ip.fetch(headers["host"]).split(':')
  port ||= 80
  @out_socket ||= TCPSocket.new(host, port.to_i)
end

#ready_socketsObject



105
106
107
108
109
110
111
112
# File 'lib/proxi/connection.rb', line 105

def ready_sockets
  if @new
    sockets = [in_socket]
  else
    sockets = [in_socket, out_socket]
  end
  IO.select(sockets).first
end