package com.example.agvcontroller.socket;
|
|
import com.example.agvcontroller.protocol.ProtocolDecoder;
|
import com.example.agvcontroller.protocol.ProtocolEncoder;
|
|
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<SocketChannel>() {
|
@Override
|
public void initChannel(SocketChannel ch) throws Exception {
|
ch.pipeline().addLast(new ProtocolEncoder()).addLast(new ProtocolDecoder(4096)).addLast(new NettyServerHandler());
|
}
|
})
|
// .addLast(new NettyServerHandler())
|
// .childHandler(new ChannelInitializer<Channel>(){
|
//
|
// @Override
|
// protected void initChannel(Channel ch) throws Exception {
|
// ch.pipeline().addLast(new ProtocolEncoder());
|
// }
|
// })
|
.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();
|
}
|
}
|
}
|