76 lines
2.6 KiB
C#
76 lines
2.6 KiB
C#
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, Action<PacketSession, ArraySegment<byte>, ushort>> _onRecv = new Dictionary<ushort, Action<PacketSession, ArraySegment<byte>, ushort>>();
|
|
Dictionary<ushort, Action<PacketSession, ArraySegment<byte>>> _handler = new Dictionary<ushort, Action<PacketSession, ArraySegment<byte>>>();
|
|
|
|
public Action<PacketSession, ArraySegment<byte>, ushort> CustomHandler { get; set; }
|
|
|
|
public void Register()
|
|
{
|
|
_onRecv.Add((ushort)EnumMessageId.C2S_INSERT_UniqueKey, MakePacket<C2S_INSERT_UniqueKey>);
|
|
_handler.Add((ushort)EnumMessageId.C2S_INSERT_UniqueKey, PacketHandler.C2S_INSERT_UniqueKeyHandler);
|
|
}
|
|
|
|
public void OnRecvPacket(PacketSession session, ArraySegment<byte> 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;
|
|
|
|
ushort packetSize = (ushort)(buffer.Count - count);
|
|
byte[] packet = new byte[packetSize];
|
|
Array.Copy(buffer.ToArray(), count, packet, 0, packetSize);
|
|
|
|
if (_onRecv.TryGetValue(id, out var action))
|
|
action.Invoke(session, packet, id);
|
|
}
|
|
|
|
void MakePacket<T>(PacketSession session, ArraySegment<byte> buffer, ushort id) where T : new()
|
|
{
|
|
// T pkt = new T();
|
|
//pkt.MergeFrom(buffer.Array, buffer.Offset + 4, buffer.Count - 4);
|
|
|
|
if (CustomHandler != null)
|
|
{
|
|
CustomHandler.Invoke(session, buffer, id);
|
|
}
|
|
else
|
|
{
|
|
Action<PacketSession, ArraySegment<byte>> action = null;
|
|
if (_handler.TryGetValue(id, out action))
|
|
action.Invoke(session, buffer);
|
|
}
|
|
}
|
|
|
|
public Action<PacketSession, ArraySegment<byte>> GetPacketHandler(ushort id)
|
|
{
|
|
Action<PacketSession, ArraySegment<byte>> action = null;
|
|
if (_handler.TryGetValue(id, out action))
|
|
return action;
|
|
return null;
|
|
}
|
|
}
|
|
}
|