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.InputStream;
import java.net.Socket;

/**
 * 接收线程类
 *
 * @author zehong
 */
public class ReceiverThread extends Thread {
    private static final Logger log = LoggerFactory.getLogger(ReceiverThread.class);
    public static String hexResponse;
    private final Socket socket;
    public ReceiverThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = in.read(buffer)) != -1) {
                byte[] responseBytes = new byte[bytesRead];
                System.arraycopy(buffer, 0, responseBytes, 0, bytesRead);

                // 将接收到的字节转换为十六进制字符串显示
                hexResponse = HexUtils.bytesToHex(responseBytes);
                log.info("收到服务器响应: " + hexResponse);
                // 老化柜58，上电断电24，写时间26
                if(hexResponse.length() == 58 || hexResponse.length() == 24 || hexResponse.length() == 26) {
                    break;
                }
            }
        } catch (IOException e) {
            log.error("接收数据失败: " + e.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
