using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SystemX.Core.Communication; namespace HubX.Library.Socket.Packet { public class PacketManager { #region Singleton static PacketManager _instance = new PacketManager(); public static PacketManager Instance { get { return _instance; } } #endregion PacketManager() { Register(); } Dictionary, ushort>> _onRecv = new Dictionary, ushort>>(); Dictionary> _handler = new Dictionary>(); public Action CustomHandler { get; set; } public void Register() { _onRecv.Add((ushort)EnumMessageId.C2S_INSERT_UniqueKey, MakePacket); _handler.Add((ushort)EnumMessageId.C2S_INSERT_UniqueKey, PacketHandler.C2S_INSERT_UniqueKeyHandler); } public void OnRecvPacket(PacketSession session, ArraySegment buffer) { ushort count = 0; ushort size = BitConverter.ToUInt16(buffer.Array, buffer.Offset); count += 2; ushort id = BitConverter.ToUInt16(buffer.Array, buffer.Offset + count); count += 2; Action, ushort> action = null; if (_onRecv.TryGetValue(id, out action)) action.Invoke(session, buffer, id); } void MakePacket(PacketSession session, ArraySegment buffer, ushort id) where T : IMessage, new() { T pkt = new T(); //pkt.MergeFrom(buffer.Array, buffer.Offset + 4, buffer.Count - 4); if (CustomHandler != null) { CustomHandler.Invoke(session, pkt, id); } else { Action action = null; if (_handler.TryGetValue(id, out action)) action.Invoke(session, pkt); } } public Action GetPacketHandler(ushort id) { Action action = null; if (_handler.TryGetValue(id, out action)) return action; return null; } } }