12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- 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)
- {
- try
- {
- var msgType = _generator.IdToType(protoId);
- _codedInput.Reset(bytes, offset, size);
- var json = _codedInput.ReadString(size - offset); //json消息,使用外部传入的长度
- msg = XJson.ToObject(json, msgType) as IMessage;
- }
- catch (Exception ex)
- {
- Log.Exception($"[Net] message read exception.", ex);
- msg = null;
- }
- }
- void IDisposable.Dispose()
- {
- _generator = null;
- }
- }
- }
|