C# - NetworkStream.Read - 填充整个缓冲区的正确方法(否则抛出异常) [英] C# - NetworkStream.Read - correct way to fill the entire buffer (or throw exceptions otherwise)

查看:48
本文介绍了C# - NetworkStream.Read - 填充整个缓冲区的正确方法(否则抛出异常)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NetworkStream.Read 方法文档指出它在两种情况下返回零:

The NetworkStream.Read method documentation states that it returns zero on two cases:

  • 如果没有可供读取的数据,Read 方法返回 0."
  • 如果远程主机关闭了连接,并且已经接收到所有可用数据,Read 方法会立即完成并返回零字节."

还有以下观察:

通过调用 CanRead 属性检查 NetworkStream 是否可读.如果您尝试从不可读的 NetworkStream 中读取数据,您将收到 IOException.

Check to see if the NetworkStream is readable by calling the CanRead property. If you attempt to read from a NetworkStream that is not readable, you will get an IOException.

我对此很困惑.我怎么知道我可以继续阅读还是应该停止阅读?

I'm very confused about it. How do I know that I can keep reading or that I should stop trying to read?

采用以下示例方法:

void Receive(byte[] buffer)
{
    int idx = 0;
    while (idx < buffer.Length)
    {
        if (input.CanRead)
        {
            int read = input.Read(buffer, idx, buffer.Length - idx);

            if (read == 0)
            {
                // ???
            }

            idx += read;
        }
        else
        {
            throw new MyLibConnectionClosedException("Cannot receive because the connection was closed");
        }
    }
}

它应该填满整个缓冲区或者它应该抛出一个异常(如果连接被关闭或丢失).这样做的正确方法是什么?

It should fill the entire buffer or it should throw an exception (if the connection was closed or lost). What is the correct way to do that?

推荐答案

采用基于证据的方法来确定事实...如果您查看 Stream.CopyTo 的源代码,它依赖于关于方法 Stream.InternalCopyTo您将看到以下用于将一个流复制到另一个流的代码:

Taking an evidence based approach to establishing the facts... If you look at the source code for Stream.CopyTo, which relies on method Stream.InternalCopyTo you'll see the following code for copying one stream to another:

byte[] buffer = new byte[bufferSize];
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
    destination.Write(buffer, 0, read);

这让我非常清楚 0 代表流的结束,而不是现在没有什么可阅读的".

This makes it absolutely clear to me that 0 represents the end of stream and not that "there is nothing to read now".

任何认为 0 的返回值具有第二含义的建议都是不正确的,因为这会使 CopyTo 的实现不正确.

Any suggestion that a return value of 0 has a second meaning is incorrect, as this would make the implementation of CopyTo incorrect.

简而言之,要读取一个流到底,继续读取直到Read返回0(或抛出异常).

In short, to read a stream to the end, carry on reading until Read returns 0 (or an exception is thrown).

这篇关于C# - NetworkStream.Read - 填充整个缓冲区的正确方法(否则抛出异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆