package com.example.agvcontroller.socket; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class NettyServer { private final int port; private Channel serverChannel; // 用于保存服务器的 Channel private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; public NettyServer(int port) { this.port = port; } public void start() throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); serverChannel = f.channel(); // 保存服务器的 Channel serverChannel.closeFuture().sync(); } finally { stop(); } } public void stop() { if (serverChannel != null) { serverChannel.close(); // 关闭服务器的 Channel } if (workerGroup != null) { workerGroup.shutdownGracefully(); } if (bossGroup != null) { bossGroup.shutdownGracefully(); } } }