我在Netty写了一个透明的反向代理,在建立连接之后和第一个字节经过的时间之间似乎有大量的延迟(大约700ms)。
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的第一个字节进入的时间约为600毫秒
然而,当我写这样一个简单的“代理”时,
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);
}
}
}
延迟是不明显的 - 我甚至无法断言我正在路由它。我做错了什么?
答案 0 :(得分:0)
不确定延迟,但最好在调用处理程序的方法channelActive()之后开始写入通道。这将保证通道的设置和通道的管道构建并准备就绪。