BinaryReader C# - 检查是否还有剩余字节
BinaryReader C# - Check if there are bytes left
我想知道是否有任何方法或 属性 允许我们查看与 BinaryReader
关联的流中是否有可用字节可读(在我的例子中,它是NetworkStream,因为我正在执行 TCP 通信)。
我已经检查了 documentation,我看到的唯一方法是 PeekChar()
,但它只检查是否有下一个字节(字符),所以如果有很多字节要读取,制作一个 while
增加计数器的循环可能是无效的。
关于TCP通信,问题是TCP背后的应用协议不是我定义的,我只是想弄清楚它是如何工作的!当然会有一些 "length field" 会给我一些关于要读取的字节的线索,但我只是在检查它是如何工作的,所以我想到了这个问题。
BinaryReader 将阻塞,直到它读取所有需要的字节。唯一的例外是它是否检测到流结束。但是 NetworkStream 是一个开放的流,没有流结束条件。因此,您可以使用使用 peek、逐字节读取且不阻塞的基本阅读器(ReadInt、ReadDouble 等)创建 class;或者使用其他异步技术。
BinaryReader
本身没有DataAvailable
属性,但是the NetworkStream
does.
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);
}
如果您在调用 reader.ReadBytes()
时没有原始 NetworkStream 的句柄,您可以使用 the BaseStream
property.
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
关联的流中是否有可用字节可读(在我的例子中,它是NetworkStream,因为我正在执行 TCP 通信)。
我已经检查了 documentation,我看到的唯一方法是 PeekChar()
,但它只检查是否有下一个字节(字符),所以如果有很多字节要读取,制作一个 while
增加计数器的循环可能是无效的。
关于TCP通信,问题是TCP背后的应用协议不是我定义的,我只是想弄清楚它是如何工作的!当然会有一些 "length field" 会给我一些关于要读取的字节的线索,但我只是在检查它是如何工作的,所以我想到了这个问题。
BinaryReader 将阻塞,直到它读取所有需要的字节。唯一的例外是它是否检测到流结束。但是 NetworkStream 是一个开放的流,没有流结束条件。因此,您可以使用使用 peek、逐字节读取且不阻塞的基本阅读器(ReadInt、ReadDouble 等)创建 class;或者使用其他异步技术。
BinaryReader
本身没有DataAvailable
属性,但是the NetworkStream
does.
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);
}
如果您在调用 reader.ReadBytes()
时没有原始 NetworkStream 的句柄,您可以使用 the BaseStream
property.
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);
}