I am embedding my size in a Stream in the first 4 byte. When I think about it, it should be possible to do it better, but that depends.
Here is how I currently do it:
bsize = ms.Length;
tcp.GetStream().Write(BitConverter.GetBytes(bsize), 0, intsize);
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize);
As you can see, it works and it's nothing weird. I just send 2 streams, the first being the length and the other being the data.
So, there aren't many things that can be done to improve or even change this.
But my idea is: why use 2 streams when you can probably embed the size immediately on the second, so you only need to write it once?
Sadly, I am not sure how to do that, or if it's even an improvement. Here is my testing code to achieve it:
bsize = ms.Length;
ms.Write(BitConverter.GetBytes(bsize), 0, intsize);
ms.Position = 0;
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize+4);
So, I thought: why can't you just write the length to the MemoryStream
and add it before the actual data?
But, it doesn't work, and I am not sure if it's adding or overwriting data. I suppose it's overwriting, which means it won't work.
From my testing, I think Write
adds data to the end, which complicates things.
tcp.GetStream()
? \$\endgroup\$