开发者

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);
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜