123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- local protobuf = require "protobuf" --引入文件protobuf.lua
- local logger = require "logger"
- local stringify = require "stringify"
- local skynet = require "skynet"
- local logger_trace = logger.trace
- local logger_warn = logger.warn
- protobuf.register_file "../src/project/proto/game.pb"
- local packname = "game." -- 包名
- local enumname = "game.msg_cmd" --枚举名字
- local Sproto = {}
- local tmap = {}
- local function charToBinary(char)
- local binaryStr = ""
- local ascii = string.byte(char)
- for i = 7, 0, -1 do
- local bit = math.floor(ascii / 2^i) % 2
- binaryStr = binaryStr .. bit
- end
- return binaryStr
- end
- -- 定义函数将字符串转换为二进制表示
- local function stringToBinary(str)
- local binaryStr = ""
- for i = 1, #str do
- binaryStr = binaryStr .. charToBinary(str:sub(i, i)) .. " "
- end
- return binaryStr
- end
- Sproto.enum_id = function (name)
- local ret = protobuf.enum_id(enumname, "cmd_"..name)
- if not ret then
- logger_trace("not enum:cmd_"..name)
- end
- return ret
- end
- Sproto.decode = function(msg, sz)
- if sz then
- msg = skynet.tostring(msg, sz)
- skynet.trash(msg,sz)
- end
- local e_id = string.unpack(">I4", msg)
- if not e_id then
- logger_trace("Sproto.decode not e_id")
- return
- end
-
- local name = tmap[e_id]
- if not name then
- logger_trace("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)
- logger.test("protobuf.decode:%s, size:%d, args:%s",name, #msg, stringify(ret or {}))
- local function fun(args)
- return Sproto.encode(name.."_rsp", args)
- end
- return "REQUEST", name, ret, fun
- end
- Sproto.encode = function (name, args, ...)
- logger.test("Sproto.encode: name:%s, args:%s", name, stringify(args or {}))
- 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
- else
- logger_warn("=========register_msg err, name:%s =========:", name)
- end
- end
- return Sproto
|