NetworkStream.CanRead 返回 true 但缓冲区不返回任何值
我有一个 do while 循环,它从 NetworkStream 对象读取缓冲区 while条件是networkStream.CanRead,因此只要它可以读取,就应该继续从缓冲区读取。唯一的问题是,当我从缓冲区读取并转换为字符串时,其中没有任何内容。即它是空的。
为什么会发生这种情况?
这是一个 ASP.NET(VS2005) 应用程序
@dtb 代码信息:
我正在传递一个 NetworkStream
对象 networkStream
// between 2 functions in a loop
{
SendMessage(networkStream, message);
ReadMessage(networkStream);
}
有趣的是,如果它重新连接并再次连接,发送/ 阅读效果很好。这实际上是 Send 的问题(我在这里没有遇到异常)或 NetworkStream 对象的重用。这在测试 TCP 服务器上本地工作正常,但在生产中(Windows Server 2003)时我遇到了上述问题(即无法从流中读取任何内容 - 直到我实际超时(退出循环)之后) 10秒)
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CanRead
是一个静态值,指示流是否能够被读取。DataAvailable
< /a> 属性会让您知道数据是否已准备好读取。CanRead
is a static value that indicates whether or not the stream is capable of being read. TheDataAvailable
property will let you know if data is ready to read.