问题描述:

I wrote a transparent reverse proxy in Netty, and there appears to be a large amount of delay (about 700ms) between the time after the connection was established, and when the first byte goes through.

 b.connect(remoteIp, remotePort).addListener(new ChannelFutureListener() {

public void operationComplete(ChannelFuture future) throws Exception {

ByteBuf buff = future.channel().alloc().buffer();

if (IS_PING) {

buff.writeByte(-2);

buff.writeByte(1);

buff.writeByte(250);

writeString(buff, "MC|PingHost");

ByteArrayOutputStream bos = new ByteArrayOutputStream();

DataOutputStream flush = new DataOutputStream(bos);

flush.writeByte(protoVersion);

writeString(flush, remoteIp);

flush.writeInt(port);

buff.writeBytes(bos.toByteArray());

flush.close();

} else {

buff.writeByte(2);

buff.writeByte(protoVersion);

writeString(buff, username);

writeString(buff, host);

buff.writeInt(port);

}

future.channel().writeAndFlush(buff);

RelayHandler.this.hasConnection = true;

RelayHandler.this.outboundChannel = future.channel();

}

The delay between the line RelayHandler.this.hasConnection = true and when the first byte from the remote IP comes in is about 600ms

However, when I write a simple "proxy" like this,

public static void main(String[] args) throws Exception {

ServerSocket socket = new ServerSocket(25565);

Socket client = socket.accept();

DataInputStream dis = new DataInputStream(client.getInputStream());

DataOutputStream dos = new DataOutputStream(client.getOutputStream());

Socket out = new Socket("5.9.106.20", 25565);

DataOutputStream outboundDos = new DataOutputStream((out.getOutputStream()));

DataInputStream outboundDis = new DataInputStream(out.getInputStream());

while (true) {

if (dis.available() > 0) {

byte[] buff = new byte[dis.available()];

dis.read(buff);

outboundDos.write(buff);

}

if (outboundDis.available() > 0) {

byte[] buff = new byte[outboundDis.available()];

outboundDis.read(buff);

dos.write(buff);

}

}

}

The delay is unnoticeable - I couldn't even tell that I was routing it at all. What am I doing wrong?

网友答案:

Not sure about delay, but it is better to start writing to a channel after handler's method channelActive() has been called. This will guarantee that the channel is setup and channel's pipeline is constructed and ready.

相关阅读:
Top