package com.wecloud.im.tillo.netty.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
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.stereotype.Component;

@Component
@Slf4j
public class NettyStart {
    private final NettyChannelInitializer nettyChannelInitializer;
    private static EventLoopGroup boss = new NioEventLoopGroup(1);
    private static EventLoopGroup work = new NioEventLoopGroup();
    private static ServerBootstrap serverBootstrap = new ServerBootstrap();

    static {
        serverBootstrap.group(boss, work);
        //Netty4使用对象池，重用缓冲区
        serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        serverBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        //设置 心跳保活 socket 的参数选项 keepAlive
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

        // 设置不延迟发送TCP_NODELAY=true
        serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);

        // 初始化服务端可连接队列
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1000);

        // 配置io模型为nio非阻塞
        serverBootstrap.channel(NioServerSocketChannel.class);

    }

    public NettyStart(NettyChannelInitializer nettyChannelInitializer) {
        this.nettyChannelInitializer = nettyChannelInitializer;
    }


    /**
     * Netty创建全部都是实现自AbstractBootstrap。
     * 客户端的是Bootstrap，服务端的则是    ServerBootstrap。
     **/
    public void run(int port) {

        log.info( "启动netty");

        try {
            //设置过滤器
            serverBootstrap.childHandler(nettyChannelInitializer);
            // 服务器绑定端口监听
            ChannelFuture f = serverBootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭EventLoopGroup，释放掉所有资源包括创建的线程
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }

}
