A Better way to know whats coming and how much Read to make sure message is completely received and do not receive contents of next message, you should send length of each message preceeding each message here is send example:
string message = "this is a message";
byte[] bytes = Encoding.Ascii.GetBytes(message);
byte[] length = BitConvertor.GetBytes(bytes.Length); // Convert message bytes' length to bytes (Will always return 4 bytes "Size of int")
clientStream.Write(length, 0, length.Length); // Send Length
clientStream.Write(bytes , 0, bytes.Length); // Send the actual message
On Receiving side you can use mixture of Asyncrhonous and Synchnronous Read methods to get work done efficiently without blocking.
I writie the steps here, if you face any problem you can contact again.
1) Read only 4 bytes asynchronously
2) convert those 4 bytes in to int using BitConvert.ToInt32();
3) Create a Memory stream to read all the bytes fron NetworkStream into NetworkStream here is snippet
int messageSize = BitConverter.ToInt32(messageDataLengthBuffer, 0); // it was read from Asynch Read ano now we are converting it back to int
MemoryStream memstrm = new MemoryStream(); readByteCount = 0; while (messageSize > 0) { if (messageSize > messageDataBuffer.Length) readByteCount = dataStream.Read(messageDataBuffer, 0, messageDataBuffer.Length); else readByteCount = dataStream.Read(messageDataBuffer, 0, messageSize);
memstrm.Write(this.messageDataBuffer, 0, readByteCount); messageSize -= readByteCount; }
It'll exactly read the length of the message (Complete) not 1 bytes less or more.
I hope this will help.
Best Regards,
Rizwan
|