liurunyu
2024-08-15 f7e731bdc2fce4445c0d22993134c6c2b07d207b
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
72
73
74
75
76
77
78
79
80
81
82
package com.ruoyi.netty.communication;
 
 
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
 
import java.util.concurrent.TimeUnit;
 
/**
 * @author 86175
 */
@Slf4j
public class TcpServer {
 
 
    /**
     * 用于分配处理业务线程的线程组个数
     */
    protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2;
    /**
     * 业务出现线程大小
     */
    protected static final int BIZTHREADSIZE = 4;
    /**
     * 监听客户端请求
     */
    private static final EventLoopGroup BOSS_GROUP = new NioEventLoopGroup(BIZGROUPSIZE);
    /**
     * 处理请求
     */
    private static final EventLoopGroup WORKER_GROUP = new NioEventLoopGroup(BIZTHREADSIZE);
 
    private static final EventExecutorGroup EXEC_GROUP = new DefaultEventExecutorGroup(100);
 
 
    public void init(String iP, Integer port) {
 
        log.info("-----------正在启动服务器,请稍后-----------");
 
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(BOSS_GROUP, WORKER_GROUP);
            b.channel(NioServerSocketChannel.class);
 
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
 
                    ChannelPipeline pipeline = socketChannel.pipeline();
 
                    pipeline.addLast(new SocketDecoder());//服务端:接受数据
                    pipeline.addLast(new SocketEncoder());//服务端:发送数据
 
                    pipeline.addLast(new ReadTimeoutHandler(ServerPeriod.TIMEOUT.getValue(), TimeUnit.SECONDS));
 
                    pipeline.addLast(EXEC_GROUP, new OptometerServerHandler());
 
                }
            });
            //缓冲区
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.bind(iP, port).sync();
            log.info("启动tcp服务器启动成功,正在监听端口:" + port + "服务器ip地址:" + iP);
        } catch (InterruptedException e) {
            log.info("tcp服务器出现异常:");
 
        }
 
 
    }
 
}