简体   繁体   中英

How to ensure that all data are read from a 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?

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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