1. @Slf4j
    2. public class CloseFutureClient {
    3. public static void main(String[] args) throws InterruptedException {
    4. NioEventLoopGroup group new NioEventLoopGroup();
    5. ChannelFuture channelFuture = new Bootstrap()
    6. .group(group)
    7. .channel(NioSocketChannel.class)
    8. .handler(new ChannelInitializer<NioSocketChannel>() {
    9. @Override // 在连接建立后被调用
    10. protected void initChannel(NioSocketChannel ch) throws Exception {
    11. ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
    12. ch.pipeline().addLast(new StringEncoder());
    13. }
    14. })
    15. .connect(new InetSocketAddress("localhost", 8080));
    16. Channel channel = channelFuture.sync().channel();
    17. log.debug("{}", channel);
    18. new Thread(()->{
    19. Scanner scanner = new Scanner(System.in);
    20. while (true) {
    21. String line = scanner.nextLine();
    22. if ("q".equals(line)) {
    23. channel.close(); // close 异步操作 1s 之后
    24. // log.debug("处理关闭之后的操作"); // 不能在这里善后
    25. break;
    26. }
    27. channel.writeAndFlush(line);
    28. }
    29. }, "input").start();
    30. // 获取 CloseFuture 对象, 1) 同步处理关闭, 2) 异步处理关闭
    31. ChannelFuture closeFuture = channel.closeFuture();
    32. /*log.debug("waiting close...");
    33. closeFuture.sync();
    34. log.debug("处理关闭之后的操作");*/
    35. closeFuture.addListener(new ChannelFutureListener() {
    36. @Override
    37. public void operationComplete(ChannelFuture future) throws Exception {
    38. log.debug("处理关闭之后的操作");
    39. group.shutdownGracefully();
    40. }
    41. });
    42. }
    43. }