Search code examples
c#tcp

check if byte array is fully sent through TCP connection c#


I have a bitmap, I converted it to bytes using BinaryFormatter and MemoryStream then sent the bytes to the TCP server, when I try to convert it back to BitMapI get this error System.Runtime.Serialization.SerializationException: End of Stream encountered before parsing was completed. I tried converting the bitmap to bytes then converting the bytes to bitmap on the client side just to check if the error is due to the conversion but everything worked just fine. So I think the problem is that the server is receiving the byte of array in chunks not in 1 big array, so my question is how check if byte array is fully sent?


Solution

  • As you say the data can absolutely be sent in multiple chunks and you need to have a way of knowing when all the data is received. For HTTP you use Content-Length in the headers to let the client know when all data is received. Since you control both sides you can transform your image into a byte array, check the size and lets say its 5000 bytes. Then you create an int (or long if necessary, not in this case probably) and set it to 5000 and send that first (as bytes) and then the rest of the data. You will then have created your own header. On the other side you start by reading the exact amount of bytes for an int (or other if you chose long etc). Then transform the bytes into an int and you know it will now come 5000 bytes. Then start reading until you have 5000 bytes. This can always be optimized but this is a simple way you can do it.