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();
}
DataAvailablejust tells you what is buffered and available locally. It means exactly nothing in terms of what is likely to arrive. The most common use ofDataAvailableis 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
Readuntil 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,\nor\rare often interpreted as “end of message”.So: it depends entirely on your protocol.