package com.huimv.lamp.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Component
public class EartagServer2 {
    @Autowired
    private EartagServerHandler2 serverHandler;
    //监听端口
    private int port = 8888;
    //创建构造方法
    public EartagServer2(){
    }

    public static void main(String[] args) throws InterruptedException {
        new EartagServer2().run();
    }
/**
 *
 * 功能描述: 启动方法前台多个服务  处理多个线程
 *
 * @param:
 * @return:
 * @auther: LiGang
 * @date: 2019/3/26 11:31
 */
    /**
     * 启动流程
     */
    public void run() throws InterruptedException {
        //配置服务端线程组
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workGroup=new NioEventLoopGroup();

        try{
            //引导整个server的启动
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)    //指定处理的连接类型
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(serverHandler);
                        }
                    });
            System.out.println("# 耳标及采集器设备数据接收服务器已经启动:"+port+"#");
            System.out.println("# 准备接收数据：");
            //绑定端口，同步等待成功
            ChannelFuture cf = serverBootstrap.bind(port).sync();
            // 等待服务端监听端口关闭
            cf.channel().closeFuture().sync();
        }finally {
            //优雅的退出
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
