HaoYueNet/Simple/ClientCore/Network/NetMsg.cs

119 lines
3.3 KiB
C#
Raw Normal View History

2023-05-25 18:04:01 +08:00
namespace ClientCore.Network
{
public class NetMsg
{
private static NetMsg instance = new NetMsg();
public static NetMsg Instance { get { return instance; } }
private Dictionary<int, List<Delegate>> netEventDic = new Dictionary<int, List<Delegate>>(128);
private NetMsg() { }
#region RegisterMsgEvent
public void RegNetMsgEvent(int cmd, Action<byte[]> callback)
{
InterRegNetMsgEvent(cmd, callback);
}
private void InterRegNetMsgEvent(int cmd, Delegate callback)
{
2024-08-23 16:18:37 +08:00
if (netEventDic.TryGetValue(cmd, out List<Delegate> dlist))
2023-05-25 18:04:01 +08:00
{
2024-08-23 16:18:37 +08:00
if (dlist.IndexOf(callback) < 0)
2023-05-25 18:04:01 +08:00
{
2024-08-23 16:18:37 +08:00
dlist.Add(callback);
2023-05-25 18:04:01 +08:00
}
}
else
{
netEventDic.Add(cmd, new List<Delegate>() { callback });
}
2024-08-23 16:18:37 +08:00
//if (netEventDic.ContainsKey(cmd))
//{
// if (netEventDic[cmd].IndexOf(callback) < 0)
// {
// netEventDic[cmd].Add(callback);
// }
//}
//else
//{
// netEventDic.Add(cmd, new List<Delegate>() { callback });
//}
2023-05-25 18:04:01 +08:00
}
#endregion
#region UnregisterCMD
public void UnregisterCMD(int evt, Action<byte[]> callback)
{
Delegate tempDelegate = callback;
InterUnregisterCMD(evt, tempDelegate);
}
private void InterUnregisterCMD(int cmd, Delegate callback)
{
2024-08-23 16:18:37 +08:00
if (netEventDic.TryGetValue(cmd, out List<Delegate> dlist))
2023-05-25 18:04:01 +08:00
{
2024-08-23 16:18:37 +08:00
dlist.Remove(callback);
if (dlist.Count == 0) netEventDic.Remove(cmd);
2023-05-25 18:04:01 +08:00
}
2024-08-23 16:18:37 +08:00
//if (netEventDic.ContainsKey(cmd))
//{
// netEventDic[cmd].Remove(callback);
// if (netEventDic[cmd].Count == 0) netEventDic.Remove(cmd);
//}
2023-05-25 18:04:01 +08:00
}
#endregion
#region PostEvent
public void PostNetMsgEvent(int cmd, byte[] arg)
{
List<Delegate> eventList = GetNetEventDicList(cmd);
if (eventList != null)
{
foreach (Delegate callback in eventList)
{
try
{
((Action<byte[]>)callback)(arg);
}
catch (Exception e)
{
App.log.Error(e.Message);
}
}
}
}
#endregion
/// <summary>
/// 获取所有事件
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
private List<Delegate> GetNetEventDicList(int cmd)
{
2024-08-23 16:18:37 +08:00
if (netEventDic.TryGetValue(cmd, out List<Delegate> dlist))
2023-05-25 18:04:01 +08:00
{
2024-08-23 16:18:37 +08:00
if (null != dlist)
2023-05-25 18:04:01 +08:00
{
2024-08-23 16:18:37 +08:00
return dlist;
2023-05-25 18:04:01 +08:00
}
}
2024-08-23 16:18:37 +08:00
//if (netEventDic.ContainsKey(cmd))
//{
// List<Delegate> tempList = netEventDic[cmd];
// if (null != tempList)
// {
// return tempList;
// }
//}
2023-05-25 18:04:01 +08:00
return null;
}
}
}