Class: Toycol::Proxy

Inherits:
Object
  • Object
show all
Includes:
Helper
Defined in:
lib/toycol/proxy.rb

Constant Summary collapse

CHUNK_SIZE =
1024 * 16

Instance Method Summary collapse

Methods included from Helper

#logger

Constructor Details

#initialize(host, port) ⇒ Proxy

Returns a new instance of Proxy.



7
8
9
10
11
12
13
14
15
16
# File 'lib/toycol/proxy.rb', line 7

def initialize(host, port)
  @host           = host
  @port           = port
  @request_method = nil
  @path           = nil
  @query          = nil
  @input          = nil
  @protocol       = Protocol
  @proxy          = TCPServer.new(@host, @port)
end

Instance Method Details

#startObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/toycol/proxy.rb', line 20

def start
  logger <<~MESSAGE
    Start proxy server on #{@protocol.protocol_name} protocol, listening on #{@host}:#{@port}
    => Use Ctrl-C to stop
  MESSAGE

  loop do
    trap(:INT) { shutdown }

    @client = @proxy.accept

    while !@client.closed? && !@client.eof?
      begin
        request = @client.readpartial(CHUNK_SIZE)
        logger "Received message: #{request.inspect.chomp}"

        safe_execution! { @protocol.run!(request) }
        assign_parsed_attributes!

        http_request_message = build_http_request_message
        logger "Message has been translated to HTTP request message: #{http_request_message.inspect}"
        transfer_to_server(http_request_message)
      rescue StandardError => e
        puts "#{e.class} #{e.message} - closing socket."
        e.backtrace.each { |l| puts "\t#{l}" }
        @proxy.close
        @client.close
      end
    end
    @client.close
  end
end