package cn.iocoder.yudao.module.remote.config.server;

import cn.iocoder.yudao.module.remote.api.robot.RemoteControllerProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
@Component
public class TCPServerApplicationRunner implements ApplicationRunner {

    @Resource
    private RemoteControllerProcessor remoteControllerProcessor;

    @Override
    public void run(ApplicationArguments args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                initServer();
            }
        }).start();
    }

    public void initServer() {
        try {
            log.info("开始初始化socket服务");
            ServerSocket server = new ServerSocket(9000);
            while (true) {
                // 监听客户端的请求,没有的话就会进行阻塞
                Socket socket = server.accept();
                remoteControllerProcessor.putSocket(socket);
                //开启一个线程进行处理客户端的请求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStream is = socket.getInputStream();
                            byte[] bytes = new byte[1024];
                            int len = is.read(bytes);
                            System.out.println(new String(bytes, 0, len));
                            OutputStream os = socket.getOutputStream();
                            //响应给客户端
                            os.write("server :".getBytes());
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (Exception e) {

        }
    }
}
