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() { @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服务器出现异常:"); } } }