networkStream.CanRead真实的,但缓冲区没有返回值缓冲区、返回值、真实、networkStream

2023-09-03 23:20:53 作者:花树下酣睡

我有while循环读取缓冲区从一个的NetworkStream对象了吗 while条件是networkStream.CanRead所以只要它可以读取它应当继续从缓冲区读取。唯一的问题是,当我从缓冲区中读取并转换为字符串,没有什么在里面。即它是空的。

为什么会发生呢?

这是一个ASP.net(VS2005)应用程序

@dtb code产品介绍:

我传递了一个网络流对象的NetworkStream

在循环2的功能之间
{
SendMessage函数(的NetworkStream,消息);

ReadMessage(的NetworkStream);
}

有趣的是,如果它重新连接并再次连接,发送/读取工作正常。它实际上与发送网络STREM对象(我正在这里也不例外),或重复使用的问题。这是工作的罚款本地测试TCP服务器上,但我得到了上面的问题,当生产(Windows Server 2003中)(即不能读取流什么 - 直到它(退出循环)后,我居然一次10秒)

ReadMessage(的NetworkStream)
{
   如果(的NetworkStream!= NULL && networkStream.CanRead)
   {
           byte []的myReadBuffer =新的字节[1024];
           StringBuilder的myCompleteMessage =新的StringBuilder();

            做
            {
                  INT numberOfBytesRead = networkStream.Read(myReadBuffer,0,myReadBuffer.Length);
                  串messageRead = Encoding.ASCII.GetString(myReadBuffer,0,numberOfBytesRead);
                  myCompleteMessage.Append(messageRead);
            }而(networkStream.CanRead);
   }
} 
QQ音乐里的歌,只要有缓冲过的,在没有网络的情况下,是否可以听呢

解决方案

的CanRead 是一个静态值,该值指示流是否为的能够被读取。该 DataAvailable 属性将让你知道,如果数据是随时阅读。

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 Network Stream 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 Network Strem 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.