package com.telpo.dipperposition.server; import com.telpo.dipperposition.handler.ServerChannelInitializer; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.stereotype.Component; import java.net.InetSocketAddress; /** * @program: DipperPositionServer * @description: 北斗定位 * @author: king * @create: 2021-01-13 14:01 */ @Slf4j @Component public class DipperPositionServer { private String serverAddr; private Integer starsAsycPort; public DipperPositionServer(ConfigurableEnvironment environment) { this.serverAddr = environment.getProperty("position-server.serverAddr"); this.starsAsycPort = Integer.parseInt(environment.getProperty("position-server.starsAsycPort")); } /* * 星历同步进程线程 */ public void start() { //new 一个主线程组 EventLoopGroup mainThreadGroup = new NioEventLoopGroup(1); //new 一个工作线程组 EventLoopGroup workThreadGroup = new NioEventLoopGroup(200); InetSocketAddress socketAddress = new InetSocketAddress(serverAddr,starsAsycPort); ServerBootstrap bootstrap = new ServerBootstrap() .group(mainThreadGroup, workThreadGroup) .channel(NioServerSocketChannel.class) .childHandler(new ServerChannelInitializer()) .localAddress(socketAddress) //设置队列大小, 多少合适???? .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 .childOption(ChannelOption.SO_KEEPALIVE, true); //绑定端口,开始接收进来的连接 try { ChannelFuture channelFuture = bootstrap.bind(socketAddress).sync(); log.info("星历服务器启动开始监听端口: {}", starsAsycPort); //log.info("服务器: {}", myServerAddr); channelFuture.addListener(future -> { if (future.isSuccess()){ log.info("start success"); }else{ log.info("start failed"); } }); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { //关闭主线程组 mainThreadGroup.shutdownGracefully(); //关闭工作线程组 workThreadGroup.shutdownGracefully(); } } }