74 lines
1.8 KiB
C#
Raw Normal View History

2020-12-12 11:27:28 +00:00
using QSB.EventsCore;
2020-12-13 22:25:23 +00:00
using QSB.Utility;
2020-12-04 22:15:41 +00:00
using QuantumUNET;
2020-12-11 23:13:13 +00:00
using QuantumUNET.Components;
2020-12-07 21:19:16 +00:00
using QuantumUNET.Messages;
2020-08-22 18:08:25 +01:00
using System;
using System.Linq;
2020-02-21 23:36:07 +01:00
namespace QSB.Messaging
{
2020-12-04 09:23:27 +00:00
public class MessageHandler<T> where T : QSBMessageBase, new()
2020-12-02 21:29:53 +00:00
{
public event Action<T> OnClientReceiveMessage;
public event Action<T> OnServerReceiveMessage;
2020-02-21 23:36:07 +01:00
2020-12-11 22:42:21 +00:00
private readonly short _eventType;
2020-12-13 22:25:23 +00:00
public EventType BaseEventType => (EventType)(_eventType - 1 - QSBMsgType.Highest);
2020-08-09 11:11:45 +02:00
2020-12-02 21:29:53 +00:00
public MessageHandler(EventType eventType)
{
2020-12-13 22:25:23 +00:00
_eventType = (short)(eventType + QSBMsgType.Highest + 1);
2020-12-02 21:29:53 +00:00
if (QSBNetworkManager.Instance.IsReady)
{
Init();
}
else
{
QSBNetworkManager.Instance.OnNetworkManagerReady += Init;
}
}
2020-12-02 21:29:53 +00:00
private void Init()
{
2020-12-11 22:42:21 +00:00
if (QSBNetworkServer.handlers.Keys.Contains(_eventType))
2020-12-02 21:29:53 +00:00
{
2020-12-11 22:42:21 +00:00
QSBNetworkServer.handlers.Remove(_eventType);
2020-12-12 11:27:28 +00:00
QSBNetworkManagerUNET.singleton.client.handlers.Remove(_eventType);
2020-12-02 21:29:53 +00:00
}
2020-12-11 22:42:21 +00:00
QSBNetworkServer.RegisterHandler(_eventType, OnServerReceiveMessageHandler);
2020-12-11 23:13:13 +00:00
QSBNetworkManagerUNET.singleton.client.RegisterHandler(_eventType, OnClientReceiveMessageHandler);
2020-12-02 21:29:53 +00:00
}
2020-02-21 23:36:07 +01:00
2020-12-02 21:29:53 +00:00
public void SendToAll(T message)
{
if (!QSBNetworkManager.Instance.IsReady)
{
return;
}
2020-12-13 22:25:23 +00:00
DebugLog.DebugWrite("SEND MESSAGE TO ALL");
2020-12-11 22:42:21 +00:00
QSBNetworkServer.SendToAll(_eventType, message);
2020-12-02 21:29:53 +00:00
}
2020-02-21 23:36:07 +01:00
2020-12-02 21:29:53 +00:00
public void SendToServer(T message)
{
if (!QSBNetworkManager.Instance.IsReady)
{
return;
}
2020-12-11 23:13:13 +00:00
QSBNetworkManagerUNET.singleton.client.Send(_eventType, message);
2020-12-02 21:29:53 +00:00
}
2020-02-21 23:36:07 +01:00
2020-12-02 21:29:53 +00:00
private void OnClientReceiveMessageHandler(QSBNetworkMessage netMsg)
{
var message = netMsg.ReadMessage<T>();
OnClientReceiveMessage?.Invoke(message);
}
2020-02-21 23:36:07 +01:00
2020-12-02 21:29:53 +00:00
private void OnServerReceiveMessageHandler(QSBNetworkMessage netMsg)
{
var message = netMsg.ReadMessage<T>();
OnServerReceiveMessage?.Invoke(message);
}
}
2020-12-03 08:28:05 +00:00
}