简体   繁体   English

BinaryReader C#-检查是否还有字节

[英]BinaryReader C# - Check if there are bytes left

I was wondering if there is any method or property that allow us to see if there are available bytes to read in the stream associated to a BinaryReader (in my case, it is a NetworkStream, since I am performing a TCP communication). 我想知道是否有任何方法或属性允许我们查看与BinaryReader关联的流中是否有可用字节读取(在我的情况下,这是一个NetworkStream,因为我正在执行TCP通信)。 I have checked the documentation and the only method I have seen is PeekChar() , but it only checks if there is a next byte (character), so in case there are many bytes to read, making a while loop to increase a counter may be inneficient. 我已经检查了文档,并且看到的唯一方法是PeekChar() ,但是它仅检查是否存在下一个字节(字符),因此,如果有许多字节要读取,则进行while循环以增加计数器可能无能为力。

Regarding the TCP communication, the problem is that the application protocol behind the TCP was not defined by me, and I am just trying to figure out how it works! 关于TCP通讯,问题在于TCP背后的应用协议不是我定义的,我只是想弄清楚它是如何工作的! Of course there will be some "length field" that will give me some clues about the bytes to read, but right know I am just checking how it works and this question came to my mind. 当然,会有一些“长度字段”为我提供有关要读取的字节的一些线索,但是正确地知道我只是在检查它的工作方式,这个问题浮现在我的脑海。

The BinaryReader itself doesn't have a DataAvailable property, but the NetworkStream does . BinaryReader本身没有DataAvailable属性,但NetworkStream

NetworkStream stream = new NetworkStream(socket);
BinaryReader reader = new BinaryReader(stream);

while (true)
{
    if (stream.DataAvailable)
    {
        // call reader.ReadBytes(...) like you normally would!
    }
    // do other stuff here!
    Thread.Sleep(100);
}

If you don't have a handle to the original NetworkStream at the point where you would call reader.ReadBytes() , you can use the BaseStream property . 如果在调用reader.ReadBytes()没有原始NetworkStream的句柄,则可以使用BaseStream属性

while (true)
{
    NetworkStream stream = reader.BaseStream as NetworkStream;
    if (stream.DataAvailable)
    {
        // call reader.ReadBytes(...) like you normally would!
    }
    // do other stuff here!
    Thread.Sleep(100);
}

BinaryReader will block until it reads all bytes required. BinaryReader将阻塞,直到读取所需的所有字节为止。 The only exception is if it detects end of stream. 唯一的例外是它检测到流的结尾。 But NetworkStream is an open stream and does not have the end of stream condition. 但是NetworkStream是开放流,没有流结束条件。 So you can either create class with basic readers (ReadInt, ReadDouble, etc) that uses peek, reads byte by byte and does not block; 因此,您可以使用基本的阅读器(ReadInt,ReadDouble等)创建类,该类使用peek,逐字节读取并且不阻塞; or use another async technology. 或使用其他异步技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM