0
点赞
收藏
分享

微信扫一扫

netty closeFuture

fbd4ffd0717b 2022-02-16 阅读 48
java
@Slf4j
public class CloseFutureClient3 {
    public static void main(String[] args) throws InterruptedException {
        // future和promise 的类型都是和异步方法配套使用,用来处理结果

        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // 异步非阻塞方法,调用线程不关心结果
                // 当前调用connect是主线程,真正执行connect的是nio 线程
                .connect(new InetSocketAddress("localhost", 8888));

        Channel channel = channelFuture.sync().channel();
        new Thread (()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String s = scanner.nextLine();
                if("q".equals(s)){
                    channel.close(); // close 异步操作 1s之后
                    break;
                }
                channel.writeAndFlush(s);
            }
        },"input").start();
        // 获取 closeFuture 对象 1)同步处理关闭 2)异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();

        // 2.2 关闭
        closeFuture.addListener((ChannelFutureListener) future -> {
            log.info("guan bi ...");
            group.shutdownGracefully();
        });
    }
}

举报

相关推荐

0 条评论