13693261870
2025-07-02 6708810c4de34dfb9513061432d656f91d56ee3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.ruoyi.fuzhou.utils.hj1239;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
 
/**
 * 数据接收解析
 */
public class DataReceiver {
    public static String receiveData(String serverIp, int serverPort) throws IOException {
        try (Socket socket = new Socket(serverIp, serverPort);
             InputStream inputStream = socket.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream.read(buffer);
            byte[] receivedData = new byte[bytesRead];
            System.arraycopy(buffer, 0, receivedData, 0, bytesRead);
            return parseData(receivedData);
        }
    }
 
    private static String parseData(byte[] data) {
        // 检查起始符和结束符
        if (data[0] != ProtocolDataEncoder.START_FLAG || data[data.length - 1] != ProtocolDataEncoder.END_FLAG) {
            throw new IllegalArgumentException("Invalid data frame");
        }
        // 提取数据段
        byte[] dataSegment = new byte[data.length - 2];
        System.arraycopy(data, 1, dataSegment, 0, dataSegment.length);
        // 校验校验码
        byte receivedChecksum = data[data.length - 2];
        byte calculatedChecksum = ProtocolDataEncoder.calculateChecksum(dataSegment);
        if (receivedChecksum != calculatedChecksum) {
            throw new IllegalArgumentException("Checksum error");
        }
        return new String(dataSegment);
    }
}