From 88fd7189755e6f73934edd0a6036e9575ef40b8d Mon Sep 17 00:00:00 2001 From: bunny <1319900154@qq.com> Date: Fri, 24 May 2024 09:15:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=96=B0=E5=A2=9E):=20:rocket:=20?= =?UTF-8?q?=E5=85=B3=E9=97=AD=E5=AE=A2=E6=88=B7=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../netty/demo3/CloseFutureClient.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 netty/service/src/main/java/cn/bunny/service/netty/demo3/CloseFutureClient.java diff --git a/netty/service/src/main/java/cn/bunny/service/netty/demo3/CloseFutureClient.java b/netty/service/src/main/java/cn/bunny/service/netty/demo3/CloseFutureClient.java new file mode 100644 index 0000000..39321fd --- /dev/null +++ b/netty/service/src/main/java/cn/bunny/service/netty/demo3/CloseFutureClient.java @@ -0,0 +1,70 @@ +package cn.bunny.service.netty.demo3; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.string.StringEncoder; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import lombok.extern.slf4j.Slf4j; + +import java.net.InetSocketAddress; +import java.util.Scanner; + +@Slf4j +public class CloseFutureClient { + public static void main(String[] args) throws InterruptedException { + NioEventLoopGroup group = new NioEventLoopGroup(); + ChannelFuture channelFuture = new Bootstrap() + .group(group) + .channel(NioSocketChannel.class) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { + nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG)); + nioSocketChannel.pipeline().addLast(new StringEncoder()); + } + }) + .connect(new InetSocketAddress("localhost", 8080)); + + Channel channel = channelFuture.sync().channel(); + new Thread(() -> { + Scanner scanner = new Scanner(System.in); + while (true) { + String line = scanner.nextLine(); + if ("q".equals(line)) { + channel.close();// 1秒之后关闭(异步)不一定是这个先关闭 + break; + } + channel.writeAndFlush(line); + } + }, "input").start(); + + // 获取CloseFuture 1、同步处理关闭 2、一步处理关闭 + ChannelFuture closeFuture = channel.closeFuture(); + // 同步关闭 + /** + * * 同步方式关闭,目前关闭控制台并没有关闭 + * log.debug("等待关闭。。。"); + * closeFuture.sync(); + * log.debug("处理完成关闭"); + * group.shutdownGracefully(); + */ + + /** + * * 异步方式关闭 + */ + closeFuture.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture channelFuture) throws Exception { + // 不是立刻停止,等待消息发送完成后在关闭 + group.shutdownGracefully(); + log.debug("处理完成关闭"); + } + }); + } +}