package com.yeejoin.amos.kgd.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: xl
 * @Description:
 * @Date: 2023/10/9 18:45
 */
@Component
public class SocketConfig {

    private static final Logger log = LoggerFactory.getLogger(SocketConfig.class);

    @Value("${amos.system.socket.port}")
    private Integer port;

    @Value("${amos.system.maas.url}")
    private String hostAndPort;

    private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    @PostConstruct
    public void socketStart() {
        //直接另起一个线程挂起Socket服务
        new Thread(this::socketServer).start();
    }

    private void socketServer() {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
            log.info("socket端口在: 【{}】中开启并持续监听=====>", port);
            while (Boolean.TRUE) {
                Socket clientSocket = ss.accept();
                //设置流读取的超时时间,这里设置为10s。超时后自动断开连接
                clientSocket.setSoTimeout(10000);
                // 创建新线程处理连接
                log.info("接收到客户端socket: {}", clientSocket.getRemoteSocketAddress());
                threadpool.execute(new ClientHandler(clientSocket,hostAndPort));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
