-- local protobuf = require "protobuf" --引入文件protobuf.lua -- --注册protobuffer文件 -- protobuf.register_file(protofile) -- ​ -- --根据注册的protofile中的类定义进行序列化,返回得到一个stringbuffer -- protobuf.encode("package.message", { ... }) -- ​ -- --根据注册的protofile中的类定义进行反序列化 -- protobuf.decode("package.message", stringbuffer) local skynet = require "skynet" local protobuf = require "protobuf" --引入文件protobuf.lua local stringify = require "stringify" protobuf.register_file "./proto/game.pb" local packname = "game." -- 包名 local Sproto = {} local tmap = {} Sproto.enum_id = function (name) local ret = protobuf.enum_id("game.msg_cmd", "cmd_"..name) if not ret then assert(false, "not enum:cmd_"..name) end return ret end Sproto.decode = function(msg) local e_id = string.unpack("I4", msg) if not e_id then skynet.error("Sproto.decode not e_id") return end local name = tmap[e_id] if not name then skynet.error("Sproto.decode not name, e_id:"..e_id) return nil, nil end local str = string.sub(msg, 5, #msg) local ret = protobuf.decode(packname..name, str) local function fun(args) return Sproto.encode(name.."_rsp", args) end return "REQUEST", name, ret, fun end Sproto.encode = function (name, args, ...) local e_id = Sproto.enum_id(name) local ret = protobuf.encode(packname..name, args) if ret and e_id then return string.pack("I4", e_id)..ret end return ret end Sproto.register_msg = function(name) local e_id = Sproto.enum_id(name) if e_id then tmap[e_id] = name end end -- skynet.start(function() -- skynet.error("protobuf game.pb") -- --编码 -- local stringbuffer = protobuf.encode("game.login", --对应person.proto协议的包名与类名 -- { -- sid = 1, -- account = 3, -- }) -- stringbuffer = string.pack("I4", 65536)..stringbuffer -- local msg = string.unpack("I4", stringbuffer) -- local str = string.sub(stringbuffer, 5, #stringbuffer) -- -- 解码 -- local data = protobuf.decode("game.login",str) -- for k, v in pairs(data or {}) do -- skynet.error(k, v) -- end -- end) skynet.start(function() skynet.error("protobuf game.pb") Sproto.register_msg("login") Sproto.register_msg("login_rsp") --编码 local code = Sproto.encode("login", { sid = 1, account = 3, }) local req, name , args, func= Sproto.decode(code) skynet.error(req, name) skynet.error(stringify(args or {})) local code2 = func({ errno = 3; }) req, name , args, func= Sproto.decode(code2) skynet.error(req, name) skynet.error(stringify(args or {})) end)