如何确保从 NetworkStream 读取所有数据 [英] How to ensure that all data are read from a NetworkStream

查看:57
本文介绍了如何确保从 NetworkStream 读取所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 DataAvailable 为 false 时,确定所有数据都是从 NetworkStream 中读取的吗?

Is sure that all data are read from a NetworkStream when DataAvailable is false?

还是数据的发送方必须先发送数据的长度.而且我必须读到我读到发送者指定的字节数?

Or does the sender of the data have to send the length of the data first. And I have to read until I have read the number of bytes specified by the sender?

样本:

private Byte[] ReadStream(NetworkStream ns)
{
    var bl = new List<Byte>();
    var receivedBytes = new Byte[128];
    while (ns.DataAvailable)
    {
            var bytesRead = ns.Read(receivedBytes, 0, receivedBytes.Length);
            if (bytesRead == receivedBytes.Length)
                bl.AddRange(receivedBytes);
            else
                bl.AddRange(receivedBytes.Take(bytesRead));
    }
    return bl.ToArray();
}

推荐答案

DataAvailable 只是告诉你什么是缓冲的和本地可用的.就可能到达的内容而言,这意味着完全没有.DataAvailable 最常见的用途是在同步读取和异步读取之间做出决定.

DataAvailable just tells you what is buffered and available locally. It means exactly nothing in terms of what is likely to arrive. The most common use of DataAvailable is to decide between a sync read and an async read.

如果您希望入站流在发送后关闭,那么您可以继续使用 Read 直到获得非肯定结果,这会告诉您已经到了尽头.如果他们正在发送多个帧,或者只是没有关闭 - 那么是的:您需要某种方式来检测帧的结尾(=逻辑消息). 可以通过长度前缀和计数,但也可以通过标记值.例如,在基于文本的协议中,\n\r 通常被解释为消息结束".

If you are expecting the inbound stream to close after the send, then you can just keep using Read until a non-positive result is achieved, which tells you it has reached the end. If they are sending multiple frames, or just aren't closing - then yes: you'll need some way of detecting the end of a frame (=logical message). That can be via a length-prefix and counting, but it can also be via sentinel values. For example, in text-based protocols, \n or \r are often interpreted as "end of message".

所以:这完全取决于您的协议.

So: it depends entirely on your protocol.

这篇关于如何确保从 NetworkStream 读取所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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