Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkStream.CanRead returns true but the buffer returns no value

I have a do while loop that reads a buffer from a NetworkStream object the while condition is networkStream.CanRead so as long as it can read, it should continue reading from the buffer. Only problem is when I read from the buffer and convert to string, there is nothing in it. i.e. its empty.

Why would that happen?

This is an ASP.NET(VS2005) application

@dtb Code Info:

I am passing the a NetworkStream object networkStream

// between 2 functions in a loop
{
    SendMessage(networkStream, message);

    ReadMessage(networkStream);
}

Funny thing is that if it reconnects and connects again, the Send/ Read works fine. Can it actually be a problem with Send ( I am getting no exceptions here) or reuse of the NetworkStream object. This is working fine locally on a test TCP server, but I am getting the above problem when in production (Windows Server 2003) (i.e. can't read anything from the stream -- until I actually time it out (exit the loop) after 10s)

ReadMessage(networkStream)
{
    if (networkStream != null && networkStream.CanRead)
    {
        byte[] myReadBuffer = new byte[1024];
        StringBuilder myCompleteMessage = new StringBuilder();

        do
        {
            int numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
            string messageRead = Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead);
            myCompleteMessage.Append(messageRead);
        } while (networkStream.CanRead);
    }
}
like image 277
soldieraman Avatar asked Feb 05 '26 06:02

soldieraman


1 Answers

CanRead is a static value that indicates whether or not the stream is capable of being read. The DataAvailable property will let you know if data is ready to read.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!