package com.jiayue.ipfcst.fileupload.IEC102;

import ch.qos.logback.classic.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 开启netty服务端
 *
 * @author xsl
 * @version 3.0
 */
@Slf4j
public class UploadFileNettyServer extends NettyParent{
//  private Logger log;
  private int readerIdleTime;
  public ChannelFuture future = null;
  private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  private final EventLoopGroup workerGroup = new NioEventLoopGroup(10);
  public String localPort = "";
  InetSocketAddress socketAddress = null;

  public UploadFileNettyServer(InetSocketAddress socketAddress,Integer readerIdleTime){
    this.socketAddress = socketAddress;
    this.readerIdleTime = readerIdleTime;
  }

  public void start() {
    ServerBootstrap bootstrap = new ServerBootstrap()
      .group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .childHandler(new ServerFor102InitChannel(readerIdleTime))
      .localAddress(socketAddress)
      //设置队列大小
      .option(ChannelOption.SO_BACKLOG, 1024)
      .childOption(ChannelOption.SO_REUSEADDR,true)
//      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
//      .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
      // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
      .childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
      this.localPort = String.valueOf(socketAddress.getPort());
      future = bootstrap.bind(socketAddress).sync();
      log.info("102服务器启动开始监听端口: {}", socketAddress.getPort());
    } catch (Exception e) {
      e.printStackTrace();
      log.error("开启102服务端口: {}失败", socketAddress.getPort(), e);
    }
  }

  /**
   * 停止服务
   */
  public void destroy() {
    log.info("Shutdown Netty Server...");
    if (future != null) {
      future.channel().close();
    }
    workerGroup.shutdownGracefully();
    bossGroup.shutdownGracefully();
    log.info("Shutdown Netty Server Success!");
  }

}
