Why not deserialized second batch of data?

What I want to do: send picture by TCP sockets.

Algorithm:
  1. The client converts the image into a byte array.
  2. Splits this array into fragments (packets).
  3. Consistently sends packets to the server.
  4. The server reads the packets, gets from them byte arrays and glue them together.
  5. Received byte array deserialized in the image.


Send (private .dll file that is connected to clientui server):
[Serializable]
 public struct DataPacket
{
 public byte[] Bytes;
 public bool IsEnclosing;
 }


How to send:
public static void SendByPackets(NetworkStream netStream, byte[] data)
{
 MemoryStream memoryStream = null;
 var formatter = new BinaryFormatter();

try
{
 for (int i = 0; i * DATA_PACKET_BYTES_MAX_LENGTH <= data.Length; i++)
{
 isLastPackage bool = ((i + 1) * DATA_PACKET_BYTES_MAX_LENGTH >= data.Length);

 var packet = new DataPacket()
{
 Bytes = SubArray<byte>(data, i * DATA_PACKET_BYTES_MAX_LENGTH, (isLastPackage) ? data.Length - i * DATA_PACKET_BYTES_MAX_LENGTH : DATA_PACKET_BYTES_MAX_LENGTH),
 IsEnclosing = isLastPackage
};

 memoryStream = new MemoryStream();
 formatter.Serialize(memoryStream, packet);

 byte[] arr = memoryStream.ToArray();

 netStream.Write(arr, 0, arr.Length);
}
}
 catch(Exception ex)
{
 throw ex;
}
finally
{
memoryStream?.Close();
}
 }</byte>


How to take:
private BitmapImage ReceiveImageByPackets(TcpClient client)
{
 NetworkStream netStream = client.GetStream();
 BinaryFormatter formatter = new BinaryFormatter();
 MemoryStream memoryStream = null;

 byte[] serializedImage = new byte[0];

do
{
 var bytes = new byte[client.ReceiveBufferSize];
 int countOfReadBytes = netStream.Read(bytes, 0, client.ReceiveBufferSize);

 if (countOfReadBytes > 0)
{
 memoryStream = new MemoryStream(bytes);
 memoryStream.Seek(0, SeekOrigin.Begin);
 var packet = (DataPacket) formatter.Deserialize(memoryStream);
memoryStream.Close();

 serializedImage = Concatenate<byte>(serializedImage, packet.Bytes);

 if (packet.IsEnclosing)
break;
}
else
 throw new Exception("Received 0 bytes!");
 } while (true);

 var stream = new MemoryStream(serializedImage);

 return (BitmapImage) formatter.Deserialize(stream);
 }</byte>


Problem: always deserializing the second package gives the error "invalid binary format input stream. The beginning of the content (in bytes): (here hex code)". What prevents to deserialize the second package? It turns out he is wrong? If so, what error?
June 5th 19 at 21:12

Find more questions by tags C#