
package com.zd.laboratory.socket.runner;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.zd.laboratory.socket.properties.SocketProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;
import java.util.concurrent.*;


/**
 * @author dgs
 * socket服务器启动类
 */

@Component
@Order(Integer.MAX_VALUE)
public class SocketRunner implements CommandLineRunner {

    //地址
    public static ConcurrentMap<String,Socket>  concurrentMap = new ConcurrentHashMap<>();
    //带端口的地址
    public static ConcurrentHashSet<String> concurrentHashSet= new ConcurrentHashSet<>();

    //黑名单
    public static ConcurrentHashSet<String> backList= new ConcurrentHashSet<>();

    public static Set<String> whitelist;
    @Autowired
    private SocketProperties properties;

    @Override
    public void run(String... args) throws Exception {

        ServerSocket server ;
        Socket socket ;
        try {
            server = new ServerSocket(properties.getPort());
            System.out.println("设备服务器已经开启, 监听端口:" + properties.getPort());
            ThreadPoolExecutor pool = new ThreadPoolExecutor(
                    properties.getPoolCore(),
                    properties.getPoolMax(),
                    properties.getPoolKeep(),
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(properties.getPoolQueueInit()),
                    new ThreadPoolExecutor.DiscardOldestPolicy()
            );
            while (true) {
                socket = server.accept();
                pool.execute(new TCPServer(socket));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

