I have a custom binary protocol response I'm receiving from a TCP server in the following format:
Response Structure
Name Length Description
Header 2 bytes Header is a fixed value Hex 0x0978.
Status 1 byte A value of 0 is Success. A value other than 0 indicates an error. A full description of each possible error is described below.
Length 4 bytes Unsigned integer of total request length including all bytes in the request (server returns little endian UInt32)
Data Variable, 0 to 1,048,576 bytes Data sent from client to server to be encoded or decoded depending on the operation being requested.
Checksum 1 byte The checksum of bytes in the request from Header to Data (i.e. excluding checksum byte).
The problem I have is that the data is of variable size, so I don't know what size to make the byte array that the response is read into from the stream. How can I achieve this?
EDIT: I want the first 7 bytes to be also included with the data in the final byte array.
Read
overloads take an offset and a length. You can read the rest of the data right after the header, within the same array. Note that you'll have a much better time performance-wise if your code, too, can handle data with an array, an offset and a length (or anArraySegment
), rather than only working on "exact" arrays, which will involve a lot of copying. – Jeroen Mostert