Oliver
Oliver

Reputation: 3682

class design on network packet parsing

I am looking for suggestions or design patterns to handle the parsing and generation of network packets (network or not by itself is not important per se). Each packet has a fixed length header and a variable length payload. The payload parsing will depend on the packet type. The straightforward way of doing this would be (assuming the input will come from a stream, console or network):

class Header {
public:
   Header(istream &);
   istream& read(istream &);
private:
   uint32_t type;
   uint32_t payload_length;
}

class PayloadTypeA {
public:
   PayloadTypeA {}
   istream& read(istream &);
private:
   uint32_t payload_1;
   uint32_t payload_2;
}

class PayloadTypeB {
 ...
}

The way I envision for the processing logic would be: read header first, then check the packet type, then decide which payload type to use to read the rest.

However, I feel this solution seems somewhat clumsy - I wonder if there is a better solution or design idioms I should follow?

thanks

Oliver

Upvotes: 3

Views: 1020

Answers (1)

Adrian
Adrian

Reputation: 5681

Usually, your header is something like this:

Contents in brackets [ ] is header data

[Header length, Data Type,] Data

If you want, you can have a dynamic header (of variable length):

[Header Length, Number of Chunks, Size of chunk 1, Size of chunk 2, Size of chunk 3 etc, Data Type,] Data

You can create your own custom header to match whatever you're sending.

Upvotes: 1

Related Questions