Netty:为什么在TimeServerHandler中使用ChannelInboundHandlerAdapter?

时间:2016-12-25 06:42:34

标签: java netty

我将浏览netty的文档here和图here。 我的问题是,Timeserver正在将时间写入套接字,以便客户端读取时间。它不应该使用ChannelOutboundHandlerAdapter吗?为什么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();
    }
}

}

2 个答案:

答案 0 :(得分:0)

我们使用ChannelInboundHandlerAdapter的原因是,我们正在写入客户端建立到服务器的通道。由于它是关于服务器的入站,我们使用ChannelInboundHandlerAdapter。客户端通过服务器发送时间的通道连接到服务器。

答案 1 :(得分:0)

由于您的服务器将响应传入的消息,因此需要实现接口 ChannelInboundHandler ,它定义了对入站事件进行操作的方法。

此外, ChannelInboundHandlerAdapter 具有简单的API,并且可以覆盖其每个方法以在适当的时间点挂钩到事件生命周期。

我刚开始学习Netty,希望这会有所帮助。 :)