package com.zehong.common.utils.TCP;

import com.zehong.common.utils.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * TCP客户端
 * 发送指令并接收信息
 * @author zehong
 */
public class TCPClient {
    private static final Logger log = LoggerFactory.getLogger(TCPClient.class);

    public static String hexResponse;

    public static String PLCConnect(String host, int port, String sendMsg){
        Socket socket = null;
        ReceiverThread receiverThread = null;
        try {
            socket = new Socket(host, port);
            log.info("连接到服务器: " + host + ":" + port);

            // 将十六进制字符串转换为字节数组
            byte[] sendData = HexUtils.hexStringToByteArray(sendMsg);

            // 获取输出流并发送数据
            OutputStream out = socket.getOutputStream();
            out.write(sendData);
            out.flush();
            log.info("已发送数据: " + sendMsg);

            receiverThread = new ReceiverThread(socket);
            receiverThread.start();
            receiverThread.join();

            hexResponse = ReceiverThread.hexResponse;
        } catch (IOException e) {
            System.err.println("通信异常: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return hexResponse;
    }
}