package com.yx.face.netty_client;

import io.netty.bootstrap.Bootstrap;
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.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: face-server
 * @Package: com.yx.face.nettyserver
 * @ClassName: NettyClient
 * @Author: 崔哥
 * @Description: 接收自有项目消息
 * @Date: 2021/11/22 13:18
 * @Version: 1.0
 */
@Component
@Slf4j
public class NettyClient {

    private static int port = 9899;
    private static String host = "127.0.0.1";
    public static Bootstrap bootstrap = null;
    public static SocketChannel socketChannel = null;
    public static ChannelFuture future = null;
    public Map<String, Bootstrap> map = new HashMap<>();

    /**
     * 向监管平台发送消息
     *
     * @param msg 接收到的自有项目传递过来的消息
     * @return
     * @throws InterruptedException
     */
    @Async
    @SneakyThrows
    public void sendMessage(String msg) {
        if (!map.containsKey(host)) {
            log.info("-------------------------新建连接服务端：" + host + "：" + port + "---------------------------");
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(eventLoopGroup);
            bootstrap.remoteAddress(host, port);
            // 设置超时时间
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);
            map.put(host, bootstrap);
        } else {
            log.info("--------------------------已连接服务端：" + host + "：" + port + "-----------------------------");
            bootstrap = map.get(host);
        }
        NettyChannelInitializer customerChannelInitializer = new NettyChannelInitializer(msg);
        bootstrap.handler(customerChannelInitializer);

        future = bootstrap.connect(host, port).sync();
        if (future.isSuccess()) {
            socketChannel = (SocketChannel) future.channel();
            log.info("远程服务器已经连接, 可以进行数据交换..");
        }
    }
}
