Netty 组件介绍 - ChannelFuture
异步处理
Netty中所有的IO操作都是异步的,操作可能不会马上返回结果。所以需要在之后的某个时间点确定他结果的方法。
-
使用sync方法同步结果
-
使用addListener(回调对象)方法异步处理结果
public class IoEventLoopClient {private static final Logger logger = LoggerFactory.getLogger(EventLoop.class);public static void main(String[] args) throws InterruptedException {ChannelFuture future = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {ch.pipeline().addLast(new StringEncoder());}}).connect(new InetSocketAddress("127.0.0.1", 8080));//1、使用sync方法同步结果ChannelFuture channelFuture = future.sync();Channel channel = channelFuture.channel();System.out.println(channel);//2、使用addListener(回调对象)方法异步处理结果channelFuture.addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture channelFuture) throws Exception {Channel channel = channelFuture.channel();System.out.println(channel);}});}
}
关闭处理
public class CloseClient {private static final Logger logger = LoggerFactory.getLogger(EventLoop.class);public static void main(String[] args) throws InterruptedException {NioEventLoopGroup group = new NioEventLoopGroup();ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {@Overrideprotected void initChannel(NioSocketChannel ch) throws Exception {ch.pipeline().addLast(new StringEncoder());}}).connect(new InetSocketAddress("127.0.0.1", 8080));Channel channel = future.sync().channel();ChannelFuture closeFuture = channel.closeFuture();//1、使用sync方法同步处理关闭closeFuture.sync();logger.info("处理关闭");//2、使用addListener(回调对象)方法异步处理结果closeFuture.addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture channelFuture) throws Exception {logger.info("处理关闭");group.shutdownGracefully();//优雅停止}});}
}