networkUtil.lua 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. local cjson = require("cjson")
  2. local slen = string.len
  3. _LOG_RECV_NET_MSG = {}
  4. _LOG_RECV_ABLE = false
  5. _LOG_SEND_NET_MSG = {}
  6. _LOG_SEND_ABLE = false
  7. function LuaRegisterMsgHandler(msgID, netCB)
  8. global.networkCtl:RegisterLuaHandler(msgID, function(msg)
  9. netCB(msg)
  10. -- 统计收到服务端的消息号
  11. if _DEBUG and _LOG_RECV_ABLE then
  12. _LOG_RECV_NET_MSG[msgID] = _LOG_RECV_NET_MSG[msgID] or {}
  13. _LOG_RECV_NET_MSG[msgID].hits = (_LOG_RECV_NET_MSG[msgID].hits or 0) + 1
  14. _LOG_RECV_NET_MSG[msgID].msgId = msgID
  15. _LOG_RECV_NET_MSG[msgID].dataLen = msg:GetDataLength()
  16. end
  17. end)
  18. end
  19. function LuaSendMsg(...)
  20. global.networkCtl:SendMsg(...)
  21. -- 统计收到服务端的消息号
  22. if _DEBUG and _LOG_SEND_ABLE then
  23. local data = {...}
  24. local msgID = data[1]
  25. local dataLen = data[7]
  26. _LOG_SEND_NET_MSG[msgID] = _LOG_SEND_NET_MSG[msgID] or {}
  27. _LOG_SEND_NET_MSG[msgID].hits = (_LOG_SEND_NET_MSG[msgID].hits or 0) + 1
  28. _LOG_SEND_NET_MSG[msgID].msgId = msgID
  29. _LOG_SEND_NET_MSG[msgID].dataLen = dataLen or 0
  30. end
  31. end
  32. function SendTableToServer(msgID, tableData)
  33. local jsonStr = cjson.encode(tableData)
  34. if not jsonStr then
  35. print(msgID, "json data encode error")
  36. return nil
  37. end
  38. LuaSendMsg(msgID, 0, 0, 0, 0, jsonStr, slen(jsonStr))
  39. end
  40. function SendUserIDToServer(msgID, userID)
  41. if nil == userID or type(userID) ~= "string" then
  42. print(msgID, "userID error")
  43. return nil
  44. end
  45. local sendData = {
  46. UserID = userID
  47. }
  48. SendTableToServer(msgID, sendData)
  49. end
  50. function CheckMsgDataLen(msg)
  51. local dataLen = msg:GetDataLength()
  52. local msgHdr = msg:GetHeader()
  53. if dataLen <= 0 then
  54. print(msgHdr.msgId, ": data is empty or overflowed!", dataLen)
  55. return false
  56. end
  57. return true
  58. end
  59. function ParseRawMsgToJson(msg)
  60. if not CheckMsgDataLen(msg) then
  61. return nil
  62. end
  63. local msgLen = msg:GetDataLength()
  64. local msgHdr = msg:GetHeader()
  65. local dataString = msg:GetData():ReadString(msgLen)
  66. local jsonData = nil
  67. local function decodeJson()
  68. jsonData = cjson.decode(dataString)
  69. end
  70. if pcall(decodeJson) then
  71. else
  72. print("ParseRawMsgToJson ERROR", msgHdr.msgId, dataString)
  73. end
  74. if not jsonData then
  75. print(msgHdr.msgId, ": data decode to json error!")
  76. return nil
  77. end
  78. return jsonData
  79. end