package com.wecloud.im.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 final EventLoopGroup BOSS = new NioEventLoopGroup(1);
    private static final EventLoopGroup WORK = new NioEventLoopGroup();
    private static final ServerBootstrap SERVER_BOOTSTRAP = new ServerBootstrap();

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

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

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

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

//        //read缓存区 256k
//        serverBootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
//        // write缓存区 256k
//        serverBootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);

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

    }

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


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

        log.info( "启动netty");

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

    }

}
