netty closeFuture

@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();
        });
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值