Which is preferable?
Assume this code before each:
byte[] data = Encoding.ASCII.GetBytes("Test Packet Message");
byte[] header = BitConverter.GetBytes(data.Length);
A:
clientStream.Write(header, 0, header.Length);
clientStream.Write(data, 0, data.Length);
B:
byte[] bytes = new byte[header.Length + data.Length];
Buffer.BlockCopy(header, 0, bytes, 0, header.Length);
Buffer.BlockCopy(data, 0, bytes, header.Length, data.Length);
clientStream.Write(bytes, 0, bytes.Length);
A has the benefit of not having to copy the bytes from one array to another so it is easier on the CPU (both clients and servers have to send and receive data so the A approach may be faster if sending a lot of data.
B has the benefit of only sending one packet. People talk of the overhead of sending single small packets. Also, Nagle’s algorithm may come in to play with A as evidenced from this post.
What would be nice was if there was a way too accomplish A without having to copy all the bytes from the header and data arrays to the bytes array but I’m not sure if that is possible.. Seems like there is a way to optimize it/make it more efficient but I’m not sure.
I would expect that the following method that accepts multiple buffers would achieve what you are looking for. However, I would want to test it to determine exactly what was being sent in terms of packets.
See the following post:
UDP – Can I send two datagram parts, and make the receiving end combine them into one?