1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using System;
- using XGame.Framework.Json;
- using XGame.Framework.Network.Protobuf;
- namespace XGame.Framework.Network
- {
- /// <summary>
- /// Json实现,等服务器能用字节流了再更换实现
- /// 用json反序列化的消息不用存储,用完直接丢弃
- /// </summary>
- internal class JsonSerializer : ISerializer, IDisposable
- {
- private readonly CodedOutputStream _codedOutput = new CodedOutputStream();
- private readonly CodedInputStream _codedInput = new CodedInputStream();
- private IMsgGenerator _generator;
- public JsonSerializer(IMsgGenerator generator)
- {
- _generator = generator;
- }
- void ISerializer.Write(IMessage msg, out byte[] bytes, out int offset, out int size)
- {
- bytes = SessionBufferPool.Acquire();
- offset = NetDefine.HEAD_LENGTH_REQUEST;
- _codedOutput.Buffer = bytes;
- _codedOutput.Reset(offset);
- try
- {
- var json = XJson.ToJson(msg);
- Log.Debug($"[Net] JsonSerializer write:{json}");
- _codedOutput.WriteString(json, false); //json消息,不写长度
- size = (int)_codedOutput.Position - offset;
- }
- catch (Exception ex)
- {
- Log.Exception($"[Net] message write exception.", ex);
- size = 0;
- }
- }
- void ISerializer.Read(byte[] bytes, int offset, int size, int protoId, out IMessage msg)
- {
- var json = string.Empty;
- try
- {
- var msgType = _generator.IdToType(protoId);
- _codedInput.Reset(bytes, offset, size);
- json = _codedInput.ReadString(size - offset); //json消息,使用外部传入的长度
- msg = XJson.ToObject(json, msgType) as IMessage;
- }
- catch (Exception ex)
- {
- Log.Exception($"[Net] message json exception: Proto:{protoId} Json:{json}.", ex);
- msg = null;
- }
- }
- void IDisposable.Dispose()
- {
- _generator = null;
- }
- }
- }
|