quantum-space-buddies/QuantumUNET/QNetworkMessageHandlers.cs

60 lines
1.6 KiB
C#
Raw Normal View History

2020-12-23 13:48:31 +00:00
using QuantumUNET.Logging;
using QuantumUNET.Messages;
2020-12-07 21:19:16 +00:00
using System.Collections.Generic;
2020-12-02 12:42:26 +00:00
2020-12-04 22:14:53 +00:00
namespace QuantumUNET
2020-12-02 12:42:26 +00:00
{
2020-12-23 12:58:45 +00:00
internal class QNetworkMessageHandlers
2020-12-02 12:42:26 +00:00
{
2021-11-20 19:55:54 +00:00
private readonly Dictionary<short, QNetworkMessageDelegate> _msgHandlers = new();
2020-12-03 11:56:32 +00:00
2020-12-23 12:58:45 +00:00
internal void RegisterHandlerSafe(short msgType, QNetworkMessageDelegate handler)
2020-12-02 12:42:26 +00:00
{
if (handler == null)
{
QLog.Error($"RegisterHandlerSafe id:{msgType} handler is null");
2020-12-02 12:42:26 +00:00
}
else
{
QLog.Debug($"RegisterHandlerSafe id:{msgType} handler:{handler.GetMethodName()}");
2020-12-03 11:56:32 +00:00
if (!_msgHandlers.ContainsKey(msgType))
2020-12-02 12:42:26 +00:00
{
2020-12-03 11:56:32 +00:00
_msgHandlers.Add(msgType, handler);
2020-12-02 12:42:26 +00:00
}
}
}
2020-12-23 12:58:45 +00:00
public void RegisterHandler(short msgType, QNetworkMessageDelegate handler)
2020-12-02 12:42:26 +00:00
{
if (handler == null)
{
QLog.Error($"RegisterHandler id:{msgType} handler is null");
2020-12-02 12:42:26 +00:00
}
else if (msgType <= 31)
{
QLog.Error($"RegisterHandler: Cannot replace system message handler {msgType}");
2020-12-02 12:42:26 +00:00
}
else
{
2020-12-03 11:56:32 +00:00
if (_msgHandlers.ContainsKey(msgType))
2020-12-02 12:42:26 +00:00
{
2020-12-23 13:48:31 +00:00
QLog.Log($"RegisterHandler replacing {msgType}");
2020-12-03 11:56:32 +00:00
_msgHandlers.Remove(msgType);
2020-12-02 12:42:26 +00:00
}
2021-06-18 21:39:21 +00:00
QLog.Debug($"RegisterHandler id:{msgType} handler:{handler.GetMethodName()}");
2020-12-03 11:56:32 +00:00
_msgHandlers.Add(msgType, handler);
2020-12-02 12:42:26 +00:00
}
}
public void UnregisterHandler(short msgType) =>
_msgHandlers.Remove(msgType);
2020-12-02 12:42:26 +00:00
2020-12-23 12:58:45 +00:00
internal QNetworkMessageDelegate GetHandler(short msgType) =>
_msgHandlers.ContainsKey(msgType) ? _msgHandlers[msgType] : null;
2020-12-02 12:42:26 +00:00
2020-12-23 12:58:45 +00:00
internal Dictionary<short, QNetworkMessageDelegate> GetHandlers() => _msgHandlers;
2020-12-02 12:42:26 +00:00
2020-12-03 11:56:32 +00:00
internal void ClearMessageHandlers() => _msgHandlers.Clear();
2020-12-02 12:42:26 +00:00
}
2020-12-03 08:28:05 +00:00
}