我在 Netty 中写了一个透明的反向代理,从建立连接到第一个字节通过之间似乎有很大的延迟(大约 700 毫秒)。
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();
}
RelayHandler.this.hasConnection = true 和远程IP的第一个字节进来之间的延迟大约是600ms
但是,当我像这样写一个简单的“代理”时,
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);
}
}
}
延迟是不明显的——我什至不能说我正在路由它。我究竟做错了什么?