The server is made with C + +, the message protocol is divided into two kinds, the fixed-length message and the variable-length message. The game's message protocol is not complex: Baotou, player ID, player data.
// 消息头 struct Base { int size; int id; Base(int _id, int _size) : id(_id), size(_size) {} }; // 常见的一个消息 struct RoleMsg : public Base { enum { ID = 0x001 }; int PlayerID; RoleProps prop; RoleMsg() : Base(ID, sizeof(*this)) , PlayerID(0) {} }
Each definition of a new normal message requires the writing of seven or eight lines of code. The structure of these messages is similar, and we can use the template to simplify the process of defining messages.
// 模板消息 template <typename T, unsigned I> struct StructTPL : public Base { int CharID; T prop; StructTPL() : Base(I, sizeof(*this)) {} }; // 普通消息 typedef StructTPL <RoleProps, 0x1> RoleMsg; typedef StructTPL <T2, 0x2> T2Msg; typedef StructTPL <T3, 0x3> T2Msg;
With a template, a single line can define a new message, which is much simpler than the original.
Similarly, variable-length messages can also be defined using templates, without the need for detailed explanations.
C + + uses templates to design a common message body