package com.huimv.datacollection.tcp;


import com.huimv.datacollection.service.IClientDataPacketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yinhao
 * @version 1.0
 * @date 2021/07/08 13:40
 */
@Component
public class Server implements CommandLineRunner {

    @Autowired
    private IClientDataPacketService iClientDataPacketService;

    @Override
    public void run(String... args) throws Exception {
        try {
            // 初始化服务端socket连接， 并监听8888端口的socket请求
            ServerSocket serverSocket = new ServerSocket(8888);

            System.out.println("****** I am Server, now begin to wait the client ******");
            int count = 0;


            // 处理socket请求
            Socket socket;
            while (true) {
                socket = serverSocket.accept();
                ServerThread serverThread = new ServerThread(socket, iClientDataPacketService);
                System.out.println("client host address is: " + socket.getInetAddress().getHostAddress());
                serverThread.start();
                count++;
                System.out.println("now client count is: " + count);

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