C# Deserializing a struct after receiving it through TCP

Instead of having a string represent your packet length and then subtract by the string's length to know where to start reading, you should implement proper length-prefixing. Length-prefixing combined with a data header will make you able to read every packet according to its size, then the data header will help you determine what to do with the data.

Ordinary length-prefixing adds a fixed header to every "packet" you send. To create this header you convert an integer (the length of your data) to bytes, which will result in 4 bytes, then you add the data header after that and also the rest of the packet (which is the data you want to send).

This will create the following packet structure:

[Length (4 bytes)][Header (1 byte)][Data (x byte(s))]

Reading a packet is very simple:

  1. Read the first 4 bytes (Length), convert and assign them to an integer variable.

  2. Read the next byte (the data header) and put that in a variable.

  3. Read x bytes to a byte array (where x is the integer you declared in step 1).

  4. Use the data header from step 2 to determine what to do with your data (the byte array from step 3).

In one of my previous answers you can see an example of what I just explained above.