JsonSerializer.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using XGame.Framework.Json;
  3. using XGame.Framework.Network.Protobuf;
  4. namespace XGame.Framework.Network
  5. {
  6. /// <summary>
  7. /// Json实现,等服务器能用字节流了再更换实现
  8. /// 用json反序列化的消息不用存储,用完直接丢弃
  9. /// </summary>
  10. internal class JsonSerializer : ISerializer, IDisposable
  11. {
  12. private readonly CodedOutputStream _codedOutput = new CodedOutputStream();
  13. private readonly CodedInputStream _codedInput = new CodedInputStream();
  14. private IMsgGenerator _generator;
  15. public JsonSerializer(IMsgGenerator generator)
  16. {
  17. _generator = generator;
  18. }
  19. void ISerializer.Write(IMessage msg, out byte[] bytes, out int offset, out int size)
  20. {
  21. bytes = SessionBufferPool.Acquire();
  22. offset = NetDefine.HEAD_LENGTH_REQUEST;
  23. _codedOutput.Buffer = bytes;
  24. _codedOutput.Reset(offset);
  25. try
  26. {
  27. var json = XJson.ToJson(msg);
  28. Log.Debug($"[Net] JsonSerializer write:{json}");
  29. _codedOutput.WriteString(json, false); //json消息,不写长度
  30. size = (int)_codedOutput.Position - offset;
  31. }
  32. catch (Exception ex)
  33. {
  34. Log.Exception($"[Net] message write exception.", ex);
  35. size = 0;
  36. }
  37. }
  38. void ISerializer.Read(byte[] bytes, int offset, int size, int protoId, out IMessage msg)
  39. {
  40. var json = string.Empty;
  41. try
  42. {
  43. var msgType = _generator.IdToType(protoId);
  44. _codedInput.Reset(bytes, offset, size);
  45. json = _codedInput.ReadString(size - offset); //json消息,使用外部传入的长度
  46. msg = XJson.ToObject(json, msgType) as IMessage;
  47. }
  48. catch (Exception ex)
  49. {
  50. Log.Exception($"[Net] message json exception: Proto:{protoId} Json:{json}.", ex);
  51. msg = null;
  52. }
  53. }
  54. void IDisposable.Dispose()
  55. {
  56. _generator = null;
  57. }
  58. }
  59. }