I am working on a network program and designing a Linux server using C ++. It is simple enough to develop a basic structure. I have a package 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; . . typedef struct{ HEADER head; union BODY{ LOGIN_REQ loginReq; LOGIN_RES loginRes; . . more types } }
Whenever I added more package types, I would have to change the switch statement to add more cases to handle newly added packages.
I use the type of union, so I do not need to change the whole structure of the package. Instead, I can add newly added package types to the union structure.
However, when I try to parse the raw data in order to put it in a package using the switch , I have to add every switch every time.
I think this is not a very good design, and I was wondering how I can structure the structure more flexibly.
Is there a better way to handle this (best design template)? What about relevant tutorials or links?
source share