feat(新增): 🚀 关闭客户端

This commit is contained in:
bunny 2024-05-24 09:15:11 +08:00
parent 15ace8f636
commit 88fd718975
1 changed files with 70 additions and 0 deletions

View File

@ -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<NioSocketChannel>() {
@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("处理完成关闭");
}
});
}
}