NetProtoBufDispatcher.lua.txt 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. local NetProtoBufDispatcher = {}
  2. local S2C = require("Network/S2C.lua")
  3. local pb = require("pb")
  4. local protoc = require("Base/protoc.lua")
  5. local protoBufConfig = require("Protos/ProtoBufConfig.lua")
  6. local networkManager = require("Network/NetworkManager.lua")
  7. function NetProtoBufDispatcher.SendData(msgType, tblData)
  8. local proto = protoBufConfig.tblMsgTypeToProto[msgType]
  9. if proto == nil then
  10. CS.ZLog.Log.Error(string.format("MsgType not found %s", msgType))
  11. return
  12. end
  13. local bytes = assert(pb.encode(proto, tblData))
  14. local _, szTimeFormat = require("Base/Utils.lua"):TimeNow()
  15. print("----> C2S: protobuf: message: szTimeFormat:", szTimeFormat, msgType)
  16. PrintTable(tblData,"protobuf: ")
  17. local rpcId = CS.LuaSocketManager.Send(msgType, bytes, 1, 0)
  18. end
  19. function NetProtoBufDispatcher.RecvData(serverMessage)
  20. local proto = protoBufConfig.tblMsgTypeToProto[serverMessage.msgType]
  21. if proto == nil then
  22. CS.ZLog.Log.Error(string.format("MsgType not found %s", msgType))
  23. return
  24. end
  25. cast(CS.System.Text.Encoding.UTF8, typeof(CS.System.Text.Encoding))
  26. local stream = serverMessage.msgData
  27. local szMsgData = CS.System.Text.Encoding.UTF8:GetString(stream:GetBuffer(), stream.Position, stream.Length - stream.Position)
  28. local serverProtocol = pb.decode(proto, szMsgData)
  29. local callback = S2C[serverMessage.msgType]
  30. if not callback then
  31. CS.ZLog.Log.Error(string.format("NetworkManager Get callback failed for : %s\n%s" , serverMessage.msgType, serverMessage.msgData))
  32. else
  33. callback(serverProtocol)
  34. end
  35. end
  36. local function LoadProto(szProtoFilename)
  37. local protoTextAsset = LoadResource(szProtoFilename)
  38. assert(protoc:load(protoTextAsset.text))
  39. end
  40. for _,fname in ipairs(protoBufConfig.ArrProtoFiles) do
  41. LoadProto(fname)
  42. end
  43. networkManager:RegisterDispatcher(1, NetProtoBufDispatcher)
  44. return NetProtoBufDispatcher