我有这段代码:
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;
}
不幸的是,流对象始终是TCP流,这意味着没有搜索操作。那么我该如何检查以确保我没有过度运行我在这里放置//这里评论的流?
答案 0 :(得分:3)
我认为没有办法查询NetworkStream
以查找您要查找的数据。您可能需要做的是将流提供的任何数据缓冲到另一个数据结构中,然后一旦知道它有足够的字节就解析出该结构中的对象。
NetworkStream
类提供DataAvailable
属性,告诉您是否有任何数据可供读取,Read()
方法返回一个值,指示实际检索的字节数。您应该能够使用这些值来进行所需的缓冲。
答案 1 :(得分:2)
见Skeets先生page
有时,您事先不知道流的长度(例如网络流),只想将整个批次读入缓冲区。这是一种方法:
/// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read data from</param>
public static byte[] ReadFully (Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read (buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write (buffer, 0, read);
}
}
}
这应该会给你一些想法。获得字节数组后,检查Length
将很容易。
在您的示例中,它看起来像这样:
int bytes_to_read = 4;
byte[] length_bytes = new byte[bytes_to_read];
int bytes_read = stream.Read(length_bytes, 0, length_bytes.Length);
// Check that there's at least four bytes left in the stream
if(bytes_read != bytes_to_read) break;
int bytes_in_msg = BitConverter.ToInt32(length_bytes);
byte[] msg_bytes = new byte[bytes_in_msg];
bytes_read = stream.Read(msg_bytes, 0, msg_bytes.Length);
// Check that there's enough bytes left in the stream
if(bytes_read != bytes_in_msg ) break;
...