简体   繁体   中英

Data not displayed correctly when read from TCP socket Java

I'm new to java sockets and processes. I'm trying to read information from a TCP socket, but when I received the data, some information was not displayed correctly. (I think it might be an encoding problem, the process I'm reading from is a Genivi DLT daemon).

Here is a sample of my code:

try (Socket socket = new Socket(hostname, port)) {

            InputStream input = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(input);

            BufferedReader br1 = new BufferedReader(reader);         

            String line;


            while((line = br1.readLine())!=null) {
                String s = br1.readLine();
                byte[] utf8Bytes = s.getBytes("UTF-8");
                if(s.contains("SYS"))
                    System.out.println(s);
            }

Here is a photo of how the data that should be displayed .

And here it's how it is actually displayed to the console:

ÒWAVAè5ÓrQSYS ² (PathologyCollectorCPU.cpp: getLoad(...)@69): {"Name": "Core", "cpuName": "cpu0", "percent": 33, "totalUser": 1533306, "totalNice:" 0, "totalSys": 1216838, "totalIdle": 5681926}

Does anybody has an idea why this might be, or some approaches I should take in solving my problem?

Edit: After some digging I think I have found some information about the protocol, here: https://www.autosar.org/fileadmin/user_upload/standards/foundation/1-0/AUTOSAR_PRS_DiagnosticLogAndTraceProtocol.pdf at page 16. If you have anymore further advice, it would be greatly appreciated.

You are using TCP (Transmission Control Protocol) and it sends data over the network by a stream. So you need to define the "data-length" for each package you sent.

When the client/service receives that data stream, it bases on the "data-length" value to read exactly the number of bytes for a package.

You can check out the example below for more detail:

private void __updateRecvHeaderData(byte[] bytes) {
    if (bytes.length >= Constants.HEADER_BYTES) { // header length
        byte[] header = Arrays.copyOfRange(bytes, 0, Constants.HEADER_BYTES);
        __dataSize = MessagePacker.byteToShort(header); // network to host short
        __recvHeader = false;
        // package = |2 bytes header| <content bytes> |
        byte[] data = Arrays.copyOfRange(bytes, Constants.HEADER_BYTES, __dataSize + Constants.HEADER_BYTES);
        __onRecvData(data); // recursion
    }
}

The file class can be found here: TCP receive and split the stream data by data-length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM