在服务启动的时候把ctype注册到服务中
static std::map<int, std::string> g_pb_cmd_map;
std::map<int, std::string> cmd_map = {
{ 0, "LoginReq" },
{ 1, "LoginRes" }
};
void proto_man::register_pb_cmd_map(std::map<int, std::string>& map){
std::map<int, std::string>::iterator it;
for (it = map.begin(); it != map.end(); it++){
g_pb_cmd_map[it->first] = it->second; //first = int,second=std::string
}
}
Session管理导出了3个函数
tolua_function(toLua_S, "close", lua_session_close);
tolua_function(toLua_S, "send_msg", lua_session_send_msg);
tolua_function(toLua_S, "get_address", lua_session_get_address);
重点介绍lua_session_send_msg函数
首先了解封包的协议,整个协议包含stype,ctype,utab和body
Body里面就是发送的数据,如果协议是json,body内容就是json字符串,可以直接使用,如果使用的是proto_buf协议,body里面就是protobuf的message对象
json就直接使用就可以,这里不做过多介绍,重点介绍protobuf协议的message对象
首先,在启动服务器的时候,会注册init_pf_cmd_map函数,把服务所有的ctype命令加入到g_pb_cmd_map映射表中去,key就是ctype,value就是命令名称,格式是:
g_pb_cmd_map[0] = “LoginReq”
g_pb_cmd_map[1] = “LoginRes”
lua_getfield(toLua_S, 2, "1"); 是从索引2表中取出key为“1”的value,压入到lua栈顶
执行完成后lua栈里面如上图所示
struct cmd_msg msg;
msg.stype = lua_tointeger(toLua_S, 3);
msg.ctype = lua_tointeger(toLua_S, 4);
msg.utag = lua_tointeger(toLua_S, 5);
msg.body里面存放的是protobuf对象,压入栈中后是一个lua表
首先根据ctype在g_pb_cmd_map全局映射表中得到ctype的名称,然后根据ctype名称创建一个Message对象(ctype对象的类用protobuf工具已经生好,放在程序中)
循环lua的body内容中的表,然后加入到Message对象中返回(具体封装请看protobuf操作)
session对象把封装好的数据发送给客户端