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;

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

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

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

    @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 (true) {
                Socket socket = ss.accept();
                // 创建新线程处理连接
                Thread thread = new Thread(new ClientHandler(socket));
                thread.start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
