76 lines
1.9 KiB
C#
Raw Normal View History

2020-08-22 18:08:25 +01:00
using OWML.Common;
2020-11-03 22:13:12 +00:00
using QSB.EventsCore;
2020-12-02 21:21:43 +00:00
using QSB.QuantumUNET;
2020-08-22 18:08:25 +01:00
using QSB.Utility;
using System;
using System.Linq;
2020-02-21 23:36:07 +01:00
using UnityEngine.Networking;
namespace QSB.Messaging
{
2020-12-02 21:29:53 +00:00
// Extend this to create new message handlers.
public class MessageHandler<T> where T : MessageBase, new()
{
public event Action<T> OnClientReceiveMessage;
public event Action<T> OnServerReceiveMessage;
2020-02-21 23:36:07 +01:00
2020-12-02 21:29:53 +00:00
private readonly EventType _eventType;
2020-08-09 11:11:45 +02:00
2020-12-02 21:29:53 +00:00
public MessageHandler(EventType eventType)
{
_eventType = eventType + MsgType.Highest + 1;
if (QSBNetworkManager.Instance.IsReady)
{
Init();
}
else
{
QSBNetworkManager.Instance.OnNetworkManagerReady += Init;
}
}
2020-12-02 21:29:53 +00:00
private void Init()
{
var eventName = Enum.GetName(typeof(EventType), _eventType - 1 - MsgType.Highest).ToUpper();
if (QSBNetworkServer.handlers.Keys.Contains((short)_eventType))
{
DebugLog.ToConsole($"Warning - NetworkServer already contains a handler for EventType {_eventType}", MessageType.Warning);
QSBNetworkServer.handlers.Remove((short)_eventType);
}
QSBNetworkServer.RegisterHandler((short)_eventType, OnServerReceiveMessageHandler);
QSBNetworkManager.singleton.client.RegisterHandler((short)_eventType, OnClientReceiveMessageHandler);
}
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;
}
QSBNetworkServer.SendToAll((short)_eventType, message);
}
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;
}
QSBNetworkManager.singleton.client.Send((short)_eventType, message);
}
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-02-21 23:36:07 +01:00
2020-12-02 21:29:53 +00:00
}
2020-02-21 23:36:07 +01:00
}