How to write a Netty TCP proxy (piping data between two channels)

27 Views Asked by At

I'm trying to write a fairly simple Netty based TCP proxy (not HTTP - any TCP-based protocol). Essentially, given A -> proxy -> B, I want the proxy to listen for incoming connections from A, when one arrives make an outbound connection to B, then "pipe" data between the two channels in both directions.

I've got as far as a handler on the server side with a channelActive that initiates the outbound connection to B when an incoming connection is accepted, and a channelRead that checks the outbound connection future to ensure the outbound connection is complete before passing on data (although I'm not sure if I've got this bit right because of the reference counting, etc.)

The problem I have is that one of the protocols I want to proxy has a very small initial request, so I'm seeing the following:

  1. inbound connection
  2. initiate outbound connection
  3. receive tiny binary request (4 bytes)
  4. do nothing with it because the outbound connection isn't complete
  5. outbound connection completes
  6. ...nothing... because there's no more data to read, the 4 bytes just sit buffered somewhere

I'd like to listen to completion of the outbound connection future and kick start the server-side pipeline to process already-buffered data, but I don't know how to do that. Honestly, the Netty documentation is very sparse and the Handlers and Adaptors and AdaptorHandlers and HandlerAdaptors get very confusing, very quickly!

1

There are 1 best solutions below

0
dty On

Answering my own question...

The key here is the channel AUTO_READ setting. As soon as the incoming connection is accepted (channelActive on the server side), set channel.config().setAutoRead(false). Then, once the outbound connection is established (which I do with a listener attached to the ConnectFuture returned by Bootstrap.connect(...)), we can re-enable auto read on the server side channel, and data will start to flow.