I am working on a networking program and designing a Linux server using C++. This is quite straightforward to design the basic structure. I have a packet definition with a header that has a fixed size.
typedef enum{
PACKET_LOGIN_REQ = 1,
PACKET_LOGIN_RES,
PACKET_STORE_REQ,
PACKET_STORE_RES
}PACKET_TYPES;
typedef struct {
PACKET_TYPES type;
short bodySize,
long long deviceId
}HEADER;
.
.
/*more definitions here*/
typedef struct{
HEADER head;
union BODY{
LOGIN_REQ loginReq;
LOGIN_RES loginRes;
.
.
more types
}
}
Whenever I added more packet types I would have to modify the switch statement to add more cases to handle the newly added packets.
I am using the union type so I don't have to change the entire packet structure. Instead I can add the newly added packet types into the union structure.
However, when I am trying to parse the raw data to put into the packet using a switch
statement then I have to add each switch
statement every time.
I think this is not a good design pattern and I was wondering how I can design the structure in a more flexible way.
Is there a better way to handle this (better design pattern)? What about related tutorials or references?