package com.wsm.admin.device.tcp;

import io.netty.bootstrap.ServerBootstrap;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * Created by Owen on 2019/12/3 0003 14:46
 *
 * 井盖tcp服务
 */

@Component
public class CoverTcpServer {

    private static final Logger log = LoggerFactory.getLogger(CoverTcpServer.class);

    @Async("updAsyncPool")
    public void run(int port) throws Exception {
        log.info("run startTcpServer");
        // NioEventLoopGroup是用来处理IO操作的多线程事件循环器
        // 用来接收进来的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 用来处理已经被接收的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 是一个启动NIO服务的辅助启动类
            ServerBootstrap server = new ServerBootstrap();
            // 这里告诉Channel如何接收新的连接
            server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 自定义处理类
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            // 初始化服务端可连接队列,指定了队列的大小128
            server.option(ChannelOption.SO_BACKLOG, 128);
            // 用来接收进来的连接
            server.childOption(ChannelOption.SO_KEEPALIVE, true);
            // 绑定端口，开始接收进来的连接
            ChannelFuture f = server.bind(port).sync();
            log.info("tcp:2000 端口，服务端启动成功...");
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            // 关闭EventLoopGroup，释放掉所有资源包括创建的线程
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
