Java 奈蒂:为什么在TimeServerHandler中使用ChannelInboundHandlerAdapter?
我正在浏览netty的文档和图表。 我的问题是,时间服务器正在将时间写入套接字,以便客户端读取时间。它不应该使用ChannelOutboundHandlerAdapter吗?为什么ChannelInboundHandlerAdapter中的逻辑 我不明白,请解释一下 时间服务器Java 奈蒂:为什么在TimeServerHandler中使用ChannelInboundHandlerAdapter?,java,netty,Java,Netty,我正在浏览netty的文档和图表。 我的问题是,时间服务器正在将时间写入套接字,以便客户端读取时间。它不应该使用ChannelOutboundHandlerAdapter吗?为什么ChannelInboundHandlerAdapter中的逻辑 我不明白,请解释一下 时间服务器 public class TimeServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(fin
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();
}
}
公共类时间客户端{
公共静态void main(字符串[]args)引发异常{
字符串host=args[0];
int port=Integer.parseInt(args[1]);
EventLoopGroup workerGroup=新的NioEventLoopGroup();
试一试{
引导b=新引导();/(1)
b、 组(工作组);/(2)
b、 通道(NioSocketChannel.class);//(3)
b、 选项(ChannelOption.SO_KEEPALIVE,true);/(4)
b、 处理程序(新的ChannelInitializer(){
@凌驾
public void initChannel(SocketChannel ch)引发异常{
ch.pipeline().addLast(新的TimeClientHandler());
}
});
//启动客户端。
ChannelFuture f=b.connect(主机、端口).sync();/(5)
//等待连接关闭。
f、 通道().closeFuture().sync();
}最后{
workerGroup.shutdownGracefully();
}
}
}我们使用ChannelInboundHandlerAdapter的原因是,我们正在将客户端建立的通道写入服务器。因为它是相对于服务器的入站,所以我们使用ChannelInboundHandlerAdapter。客户端通过服务器发送时间的通道连接到服务器。因为服务器将响应传入消息,所以它需要实现接口ChannelInboundHandler,该接口定义了处理入站事件的方法 此外,ChannelInboundHandlerAdapter有一个简单的API,它的每一个方法都可以被覆盖,以便在适当的时候连接到事件生命周期中 我刚开始学习Netty,希望这对我有所帮助。:)