[英]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.