1

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.

Community
  • 1
  • 1
Semant1ka
  • 547
  • 6
  • 22
  • And how would you do this if you had NetworkStream instead? The fact that DataAvalilable returns false does not mean some "end" of message is reached. – Evk Apr 28 '17 at 11:42
  • Try to make it async – 1408786user Apr 28 '17 at 11:45
  • @Evk Well, at least it helps to stop waiting, and after that people are facing the fact that they really need to wait for the real end of message. I see that one possible solution is implementing a kind of protocol... – Semant1ka Apr 28 '17 at 11:47
  • That is what I mean: if you expect to pass several messages (not just one and then close connection) - the only reliable way it to implement a protocol (like first send message length and then message itself). – Evk Apr 28 '17 at 11:49

0 Answers0