2013-10-09 26 views
0

我在Netty中编写了一个透明的反向代理,并且在建立连接之后和第一个字节通过之间似乎存在大量的延迟(大约700ms)。连接和字节之间的Netty极端延迟

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 =真,并且当从所述远程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

不确定延迟,但最好在处理程序的方法channelActive()被调用后开始写入通道。这将保证通道的设置和通道的流水线的建立和准备。