Class: Masyo::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/masyo/proxy.rb

Constant Summary collapse

TIMEOUT =
3
MAX_RECV_LEN =
1 * 1024 * 1024 * 1024

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(listen_port, server_host, server_port) ⇒ Proxy

Returns a new instance of Proxy.



22
23
24
25
26
27
28
# File 'lib/masyo/proxy.rb', line 22

def initialize(listen_port, server_host, server_port)
  Masyo.logger.info "Proxy 0.0.0.0:#{listen_port} -> #{server_host}:#{server_port}"

  @server_host = server_host
  @server_port = server_port
  @proxy = ::TCPServer.new(listen_port)
end

Instance Attribute Details

#proxyObject

Returns the value of attribute proxy.



7
8
9
# File 'lib/masyo/proxy.rb', line 7

def proxy
  @proxy
end

Class Method Details

.run(listen_port, server_host, server_port) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/masyo/proxy.rb', line 12

def run(listen_port, server_host, server_port)
  p = new(listen_port, server_host, server_port)
  p.run
rescue Interrupt
  Masyo.logger.info "Stopping..."
  # for sending buffer to receiver before socket close.
  p.stop
end

Instance Method Details

#handle(client) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/masyo/proxy.rb', line 44

def handle client
  input = receive_from client
  response = request input
  client.write response unless response.nil?
ensure
  client.close unless client.closed?
end

#request(msg) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/masyo/proxy.rb', line 52

def request msg
  ::TCPSocket.open(@server_host, @server_port) { |socket|
    socket.write msg

    receive_from socket
  }
rescue Errno::ECONNREFUSED
  Masyo.logger.error "Fail to request to server"
  nil
end

#runObject



30
31
32
33
34
35
36
37
38
# File 'lib/masyo/proxy.rb', line 30

def run
  loop {
    break if proxy.closed?

    Thread.start(proxy.accept) do |client|
      handle client
    end
  }
end

#stopObject



40
41
42
# File 'lib/masyo/proxy.rb', line 40

def stop
  proxy.close unless proxy.closed?
end