Home > Software engineering >  How to read binary data from TCP stream?
How to read binary data from TCP stream?

Time:08-27

I have a device that sends data to another device via TCP. When I receive the data and try the Encoding.Unicode.GetString() method on the Byte array, it turns into unreadable text.

Only the first frame of the TCP packet (the preamble in the header) can be converted to text. (sender TCP docs, packet data).

This is my code so far. I have tried encoding as ASCII and there are no results either.

NetworkStream stream = tcpClient.GetStream();
int i;
Byte[] buffer = new Byte[1396];

while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
{
      data = System.Text.Encoding.Unicode.GetString(buffer, 0, i);
      data = data.ToUpper();
      Console.WriteLine($"Data: {data}");
}

This just prints the same unreadable string seen in the "packet data" link above. Why is this happening? The official device doc says it is encoded in little endian. Am I missing something? I am new in handling TCP data transmission.

CodePudding user response:

There is nothing in the linked documentation to indicate that there is any textual data at all, with exception for the "preamble", that is a fixed, four letter ascii-string, or an integer with the equivalent value, whatever you prefer.

It specifies a binary header with a bunch of mostly 32-bit integers, followed by a sequence of frames, where each frame has 3 32-bit numbers.

So I would suggest using wrapping your buffer in a memory stream and use BinaryReader to read values, according to the format specification.

Note that network communication typically uses big-endian encoding, but both windows and your device uses little-endian, so you should not have to bother with endianess.

  • Related