2016-12-25 15 views
-1

私はnettyの文書hereと図hereを調べています。 私の質問は、タイムサーバがクライアントに時刻を読み込ませるためにタイムサーバがソケットに時刻を書き込んでいることです。 ChannelOutboundHandlerAdapterを使用するべきではありませんか? ChannelInboundHandlerAdapterのロジックはなぜですか?Netty:TimeServerHandlerでChannelInboundHandlerAdapterを使用する理由

説明できません。

タイムサーバ、

public class TimeServerHandler extends ChannelInboundHandlerAdapter { 

@Override 
public void channelActive(final ChannelHandlerContext ctx) { // (1) 
    final ByteBuf time = ctx.alloc().buffer(4); // (2) 
    time.writeInt((int) (System.currentTimeMillis()/1000L + 2208988800L)); 

    final ChannelFuture f = ctx.writeAndFlush(time); // (3) 
    f.addListener(new ChannelFutureListener() { 
     @Override 
     public void operationComplete(ChannelFuture future) { 
      assert f == future; 
      ctx.close(); 
     } 
    }); // (4) 
} 

@Override 
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
    cause.printStackTrace(); 
    ctx.close(); 
} 

}

TimeClient、

public class TimeClient { 
public static void main(String[] args) throws Exception { 
    String host = args[0]; 
    int port = Integer.parseInt(args[1]); 
    EventLoopGroup workerGroup = new NioEventLoopGroup(); 

    try { 
     Bootstrap b = new Bootstrap(); // (1) 
     b.group(workerGroup); // (2) 
     b.channel(NioSocketChannel.class); // (3) 
     b.option(ChannelOption.SO_KEEPALIVE, true); // (4) 
     b.handler(new ChannelInitializer<SocketChannel>() { 
      @Override 
      public void initChannel(SocketChannel ch) throws Exception { 
       ch.pipeline().addLast(new TimeClientHandler()); 
      } 
     }); 

     // Start the client. 
     ChannelFuture f = b.connect(host, port).sync(); // (5) 

     // Wait until the connection is closed. 
     f.channel().closeFuture().sync(); 
    } finally { 
     workerGroup.shutdownGracefully(); 
    } 
} 

}

答えて

0

我々が確立されたチャネルへの書き込みされ、ためChannelInboundHandlerAdapterが使用理由クライアントからサーバーに送信されます。サーバーに対するインバウンドのため、ChannelInboundHandlerAdapterを使用します。クライアントは、サーバーが時刻を送信するチャネルを通じてサーバーに接続します。