From the internet I got the way to read a huge string from a NetworkStream.
static NetworkStream ns = null;
static StringBuilder sb = null;
static byte[] buffer = null;
static int position = 0;
//.......................................
//other codes skipped for simplicity
//.......................................
private static string Read()
{
if (ns.CanRead)
{
sb.Clear();
position = 0;
while (ns.DataAvailable)
{
position = ns.Read(buffer, 0, buffer.Length);
sb.Append(Encoding.Unicode.GetString(buffer, 0, position));
}
return sb.ToString().Trim();
}
else
{
return null;
}
}
However, I cannot find an example how to write a huge string to a NetworkStream.
Is there a “symmetrical” pattern for writing as we do for reading?
Thank you in advance.
That reading code is dangerously wrong in many ways:
DataAvailableproperty to decide when it should be “done” – that’s incredibly dangerous as it means if a packet is delayed in the stream, you could read half as much data as you expected toEncoding.Unicodealways, which is rarely the best choice of encodingEncoder/Decoderclasses are for… but you don’t really need to use them here anyway – see below.I would strongly suggest that you wrap the
NetworkStreamin aStreamReaderfor reading, and aStreamWriterfor writing. That’s what they’re for. You can then read a line at a time, or just achar[]buffer, or to the end of the stream (which means “until the socket is closed”). This is fine for a text-only protocol.If you’ve got a protocol which mixes text and binary data, life becomes a lot harder. Personally I like protocols which length-prefix messages – that way you can read only the data you’re meant to, and then perform whatever conversion you want.
Anyway, I hope this random selection of thoughts helps… if you want more detailed assistance, please provide details of what protocol you’re using.