package org.example.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.example.utils.MyDecoder;
import org.example.utils.MyEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zjb
 * @since 2023-12-11 10:39:00
 */
@Component
public class BootNettySocketServer {

    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workGroup;

    @Autowired
    private BootNettySocketChannelInboundHandler bootNettySocketChannelInboundHandler;


    /**
     * 	启动服务
     */
    public void startup(int port) {
        try {
            bossGroup = new NioEventLoopGroup(1);
            workGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup);
            bootstrap.channel(NioServerSocketChannel.class);

            bootstrap.option(ChannelOption.SO_REUSEADDR, true)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.SO_RCVBUF, 10485760);

            bootstrap.childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    channelPipeline.addLast("encoder", new MyEncoder());
                    channelPipeline.addLast("decoder", new MyDecoder());
                    channelPipeline.addLast(bootNettySocketChannelInboundHandler);
                }
            });
            ChannelFuture f = bootstrap.bind(port).sync();
            if(f.isSuccess()){
                System.out.println("成功侦听端口：" + port);
                f.channel().closeFuture().sync();
            } else {
                System.out.println("侦听端口失败：" + port);
            }
        } catch (Exception e) {
            System.out.println("start exception"+e.toString());
        }
    }

}
