I have two applications one on server and one on client.
On server side I write to stream like this.
NetworkStream stream = client.GetStream();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(messageSent);
stream.Write(msg, 0, msg.Length);
stream.Write(msg, 0, msg.Length);
I am writing multiple string in stream one by one. The length of string is variable an reach max length of about 500
PROBLEM:
How to read on client side in blocks
What happen is sometimes I get combines string
Like I sent A,B,C
On client I received A, BC
I am client like this:
bytes = stream.Read(data, 0, data.Length);
Any help is appreciated.
Yes, you’ve got a stream – just a sequence of bytes – but you’re treating it as if it weren’t a stream; as if it were a message-oriented protocol.
Fundamentally, with simple stream-based communications, there’s nothing inherent to break the stream up into messages. If you want to do that, you need to build a layer on top. There are three common ways of doing this:
The second of these is probably the simplest, but has the restriction that you need to know how large the message is before you start sending it. The third option gets round this by having a variable number of blocks. I would personally avoid the first option if possible – unless you have some natural “end of message” token which you would never, ever want to include as data within the message, you have to start working out an escaping scheme, which is a pain… and it’s harder to read the data, too.
You don’t have to do all of this from scratch, of course. If you’ve got .NET on both ends, you can use
BinaryReaderandBinaryWriterwhich support length-prefixed strings, and there are plenty of serialization frameworks around too, which typically handle this in some form or other. (My personal preference is Protocol Buffers, as it’s efficient, platform-independent, and what I use at work. There are two common .NET ports – one by myself, and one by Marc Gravell.)