#
whycq
2024-08-16 5bdad72f5d5077ca875dd03cfdaafb3d7aba93da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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();
        }
    }
}