简体   繁体   中英

Tailor byte array size to NetworkStream response with protocol length included

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 (ie 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.

One possible solution:

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM