Class: TCPProxy::Connection

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

Instance Method Summary collapse

Constructor Details

#initialize(in_sock, out_sock) ⇒ Connection

Returns a new instance of Connection.



92
93
94
95
# File 'lib/tcp_proxy.rb', line 92

def initialize(in_sock, out_sock)
  @m = Mutex.new
  @in_sock, @out_sock = in_sock, out_sock
end

Instance Method Details

#closeObject



97
98
99
100
101
# File 'lib/tcp_proxy.rb', line 97

def close
  @m.synchronize {
    @in_sock.close; @in_sock = nil
    @out_sock.close; @out_sock = nil }
end

#pump(n) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/tcp_proxy.rb', line 109

def pump(n)
  while n>0
    available_sockets = [@in_sock, @out_sock]
    ready_sockets, (*) = IO.select(available_sockets, nil, nil, 0)

    break unless ready_sockets && !ready_sockets.empty?
    
    ready_sockets.each do |socket|
      buf = socket.read_nonblock(16*1024)
      
      if socket == @in_sock
        puts "--> #{buf.size}" if $DEBUG
        @out_sock.write(buf)
      else
        puts "<-- #{buf.size}" if $DEBUG
        @in_sock.write(buf)
      end
    end

    n -= 1
  end
rescue Errno::EAGAIN
  # Read would block, attempt later
end

#pump_synchronized(n = 10) ⇒ Object



103
104
105
106
107
# File 'lib/tcp_proxy.rb', line 103

def pump_synchronized(n=10)
  @m.synchronize {
    return unless @in_sock && @out_sock
    pump(n) }
end