I have a simple .net assembly which connects to server and returns opened Stream available for reading and writing. What is important that should be a Stream not a NetworkStream so I don't have a DataAvailable method there.
Now I want to use this simple assembly in console application to communicate with server: sending messages and receive answers through Stream object.
And here is the problem: while reading from socket code below hangs because of Stream.Read() will always wait for input and never return 0. This behavior described in this topic.
public static byte[] ReadFully (Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read (buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write (buffer, 0, read);
}
}
}
This code is from this article
Also I can't set ReadTimeout because I only have access to Stream object.
So what can possibly be a solution? How do I read to the whole buffer and determine when to stop?
I was just using a timeout before Stream.Read() but timeouts aren't good.
PS. I am using .net core 1.1 as a target framework, so some solutions requiring .net framework will not work for me.