pbSproto.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. local protobuf = require "protobuf" --引入文件protobuf.lua
  2. local logger = require "logger"
  3. local stringify = require "stringify"
  4. local skynet = require "skynet"
  5. local logger_trace = logger.trace
  6. local logger_warn = logger.warn
  7. protobuf.register_file "../src/project/proto/game.pb"
  8. local packname = "game." -- 包名
  9. local enumname = "game.msg_cmd" --枚举名字
  10. local Sproto = {}
  11. local tmap = {}
  12. local function charToBinary(char)
  13. local binaryStr = ""
  14. local ascii = string.byte(char)
  15. for i = 7, 0, -1 do
  16. local bit = math.floor(ascii / 2^i) % 2
  17. binaryStr = binaryStr .. bit
  18. end
  19. return binaryStr
  20. end
  21. -- 定义函数将字符串转换为二进制表示
  22. local function stringToBinary(str)
  23. local binaryStr = ""
  24. for i = 1, #str do
  25. binaryStr = binaryStr .. charToBinary(str:sub(i, i)) .. " "
  26. end
  27. return binaryStr
  28. end
  29. Sproto.enum_id = function (name)
  30. local ret = protobuf.enum_id(enumname, "cmd_"..name)
  31. if not ret then
  32. logger_trace("not enum:cmd_"..name)
  33. end
  34. return ret
  35. end
  36. Sproto.decode = function(msg, sz)
  37. if sz then
  38. msg = skynet.tostring(msg, sz)
  39. skynet.trash(msg,sz)
  40. end
  41. local e_id = string.unpack(">I4", msg)
  42. if not e_id then
  43. logger_trace("Sproto.decode not e_id")
  44. return
  45. end
  46. local name = tmap[e_id]
  47. if not name then
  48. logger_trace("Sproto.decode not name, e_id:"..e_id)
  49. return nil, nil
  50. end
  51. local str = string.sub(msg, 5, #msg)
  52. local ret = protobuf.decode(packname..name, str)
  53. logger.test("protobuf.decode:%s, size:%d, args:%s",name, #msg, stringify(ret or {}))
  54. local function fun(args)
  55. return Sproto.encode(name.."_rsp", args)
  56. end
  57. return "REQUEST", name, ret, fun
  58. end
  59. Sproto.encode = function (name, args, ...)
  60. logger.test("Sproto.encode: name:%s, args:%s", name, stringify(args or {}))
  61. local e_id = Sproto.enum_id(name)
  62. local ret = protobuf.encode(packname..name, args)
  63. if ret and e_id then
  64. return string.pack(">I4", e_id)..ret
  65. end
  66. return ret
  67. end
  68. Sproto.register_msg = function(name)
  69. local e_id = Sproto.enum_id(name)
  70. if e_id then
  71. tmap[e_id] = name
  72. else
  73. logger_warn("=========register_msg err, name:%s =========:", name)
  74. end
  75. end
  76. return Sproto