JsonSerializer.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. try
  41. {
  42. var msgType = _generator.IdToType(protoId);
  43. _codedInput.Reset(bytes, offset, size);
  44. var json = _codedInput.ReadString(size - offset); //json消息,使用外部传入的长度
  45. msg = XJson.ToObject(json, msgType) as IMessage;
  46. }
  47. catch (Exception ex)
  48. {
  49. Log.Exception($"[Net] message read exception.", ex);
  50. msg = null;
  51. }
  52. }
  53. void IDisposable.Dispose()
  54. {
  55. _generator = null;
  56. }
  57. }
  58. }