More often than node, I do the following:
- Code: Select all
class MessageHeader {
public:
int type;
int length;
byte protocol;
byte requestId;
virtual void read(Buffer b) = 0 {
b.read(type);
b.read(length);
b.read(protocol);
b.read(requestId);
}
virtual void write(Buffer b) = 0 {
b.write(type);
b.write(length);
b.write(protocol);
b.write(requestId);
}
};
class Message : public MessageHeader {
public:
int length;
MessageItem items[MAX_ITEMS];
virtual void read(Buffer b) {
MessageHeader::read(b);
b.read(length);
for(int i = 0; i < length; ++i) {
items[i].read(b);
}
}
virtual void write(Buffer b) {
MessageHeader::write(b);
b.write(length);
for(int i = 0; i < length; ++i) {
items[i].write(b);
}
}
};
switch (msg.type) {
case MSG_A:
return new Message1(buffer);
case MSG_B:
return new Message2(buffer);
...
}
I think all the above boilerplate code could easily be made substantially smaller if a library allowed to:
- declare message structures and message fields with names, default values, ranges, etc.
- automate reading and writing from/to buffers.
- take care of endianess automatically (after the user chooses the appropriate endianess once).
- automatic construction of the appropriate message instance, depending on the contents of the received buffer.
- automatically convert enumerated values to/from integers.
- automatically validate messages.
The library would be similar in purpose to Google's Protocol Buffers library, but without the external tools, i.e. messages would only be constructed by code.





