How to ensure that all data are read from a NetworkStream

给你一囗甜甜゛ 提交于 2019-12-11 01:12:28

问题


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?

Sampel:

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();
}

回答1:


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.

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.




回答2:


The easiest way would be to have a start/end character, so the message would be:

string message = "Hello";
string messageToSend = (char)2 + message + (char)3;


来源:https://stackoverflow.com/questions/14709781/how-to-ensure-that-all-data-are-read-from-a-networkstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!