Class: BWA::Proxy

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

Instance Method Summary collapse

Constructor Details

#initialize(host, port: 4257) ⇒ Proxy

Returns a new instance of Proxy.



9
10
11
12
# File 'lib/bwa/proxy.rb', line 9

def initialize(host, port: 4257)
  @host, @port = host, port
  @listen_socket = TCPServer.open(port)
end

Instance Method Details

#runObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/bwa/proxy.rb', line 14

def run
  client_socket = @listen_socket.accept
  server_socket = TCPSocket.new(@host, @port)
  t1 = Thread.new do
    shuffle_messages(client_socket, server_socket, "Client")
  end
  t2 = Thread.new do
    shuffle_messages(server_socket, client_socket, "Server")
  end
  t1.join
  t2.join
end

#shuffle_messages(socket1, socket2, tag) ⇒ Object



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
52
53
# File 'lib/bwa/proxy.rb', line 27

def shuffle_messages(socket1, socket2, tag)
  leftover_data = "".b
  loop do
    if leftover_data.length < 2 || leftover_data.length < leftover_data[1].ord + 2
      begin
        leftover_data += socket1.recv(128)
      rescue Errno::EBADF
        # we closed it on ourselves
        break
      end
    end
    if leftover_data.empty?
      socket2.close
      break
    end
    data_length = leftover_data[1].ord
    data = leftover_data[0...(data_length + 2)]
    leftover_data = leftover_data[(data_length + 2)..-1] || ""
    begin
      message = Message.parse(data)
      BWA.logger.info "#{tag}: #{message.inspect}"
    rescue InvalidMessage => e
      BWA.logger.info "#{tag}: #{e}"
    end
    socket2.send(data, 0)
  end
end