![](/img/trans.png)
[英]How to estimate the size of byte array/buffer to read from NetworkStream?
[英]Tailor byte array size to NetworkStream response with protocol length included
我从TCP服务器收到以下格式的自定义二进制协议响应:
回应结构
名称 长度描述
标头 2个字节标头是固定值十六进制0x0978。
状态 1字节值为0表示成功。 0以外的值表示错误。 每个可能的错误的完整描述如下。
长度 4个字节 ,包括请求中所有字节的请求总长度的无符号整数(服务器返回小端UInt32)
数据 变量,0到1,048,576字节从客户端发送到服务器的数据,根据请求的操作进行编码或解码。
校验和 1个字节从报头到数据的请求中字节的校验和(即,不包括校验和字节)。
我的问题是数据大小可变,因此我不知道要从响应流中读取响应的字节数组的大小。 我该如何实现?
编辑:我希望前7个字节也包含在最终字节数组中的数据中。
一种可能的解决方案:
class Program
{
private static byte[] data = new byte[8]
{
// header
0,
0,
// status
1,
// message size
8,
0,
0,
0,
// data
1
};
static byte[] Read(Stream stream)
{
const int headerLength = 7;
const int sizePosition = 3;
var buffer = new byte[headerLength];
stream.Read(buffer, 0, headerLength);
// for BitConverter to work
// the order of bytes in the array must
// reflect the endianness of the computer system's architecture
var size = BitConverter.ToUInt32(buffer, sizePosition);
var result = new byte[size];
Array.Copy(buffer, result, headerLength);
stream.Read(result, headerLength, (int)size - headerLength);
return result;
}
static void Main(string[] args)
{
var stream = new MemoryStream(data);
byte[] bytes = Read(stream);
foreach (var b in bytes)
{
Console.WriteLine(b);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.