I have this code:
public static List<ReplicableObject> ParseStreamForObjects(Stream stream)
{
List<ReplicableObject> result = new List<ReplicableObject>();
while (true)
{
// HERE I want to check that there's at least four bytes left in the stream
BinaryReader br = new BinaryReader(stream);
int length = br.ReadInt32();
// HERE I want to check that there's enough bytes left in the stream
byte[] bytes = br.ReadBytes(length);
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
result.Add((ReplicableObject) Formatter.Deserialize(ms));
ms.Close();
br.Close();
}
return result;
}
Unfortunately, the stream object is always going to be a TCP stream, which means no seek operations. So how can I check to make sure that I’m not over-running the stream where I’ve put the // HERE comments?
I don’t think there’s any way to query a
NetworkStreamto find the data you’re looking for. What you’ll probably need to do is buffer whatever data the stream makes available into another data structure, then parse objects out of that structure once you know it’s got enough bytes in it.The
NetworkStreamclass provides aDataAvailableproperty that tells you if any data is available to be read, and theRead()method returns a value indicating how many bytes it actually retrieved. You should be able to use those values to do the buffering you need.