package com.zksy.audio.config;

import com.zksy.audio.utils.MessageHandler;
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 io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NettyServerThread {
	@Value("${netty.port:8313}")
	private int port;
	private static Logger logger = LoggerFactory.getLogger(NettyServerThread.class);
	private final MessageHandler messageHandler;
	@Autowired
	public NettyServerThread(MessageHandler messageHandler) {
		this.messageHandler = messageHandler;
	}
	public void startServer() {
		System.out.println("Netty服务启动端口号" + port);
		EventLoopGroup acceptor = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		NettyServer.acceptor = acceptor;
		NettyServer.worker = worker;
		ServerBootstrap bootstrap = new ServerBootstrap();

		// 添加boss和worker组
		bootstrap.group(acceptor, worker);
		//这句是指定允许等待accept的最大连接数量,我只需要连一个客户端,这里就关掉了,java默认是50个
		// bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
		bootstrap.option(ChannelOption.TCP_NODELAY, true);
		// 用于构造socketchannel工厂
		bootstrap.channel(NioServerSocketChannel.class);

		/**
		 * 传入自定义客户端Handle（处理消息）
		 */
		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				logger.info("来自" + ch.remoteAddress() + "的新连接接入");
				// 注册handler
				ch.pipeline().addLast(new ReadTimeoutHandler(3600));// 超时时间,1小时内没有从通道（Channel）读取到任何数据
				ch.pipeline().addLast(messageHandler);
			}
		});

		// 绑定端口，开始接收进来的连接
		ChannelFuture f;
		try {
			f = bootstrap.bind(port).sync();
			// 等待服务器 socket 关闭 。
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (acceptor != null) {
				acceptor.shutdownGracefully();
			}
			if (worker != null) {
				worker.shutdownGracefully();
			}
		}
	}
}