76 lines
2.3 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
{
// Extend this to create new message handlers.
2020-11-04 09:34:01 +00:00
public class MessageHandler<T> where T : MessageBase, new()
2020-02-21 23:36:07 +01:00
{
public event Action<T> OnClientReceiveMessage;
public event Action<T> OnServerReceiveMessage;
2020-08-22 18:08:25 +01:00
private readonly EventType _eventType;
2020-08-09 11:11:45 +02:00
2020-11-04 09:34:01 +00:00
public MessageHandler(EventType eventType)
{
2020-08-22 18:08:25 +01:00
_eventType = eventType + MsgType.Highest + 1;
2020-08-18 22:37:27 +02:00
if (QSBNetworkManager.Instance.IsReady)
{
Init();
}
else
{
2020-08-18 22:37:27 +02:00
QSBNetworkManager.Instance.OnNetworkManagerReady += Init;
}
}
private void Init()
2020-02-21 23:36:07 +01:00
{
2020-09-22 21:39:53 +01:00
var eventName = Enum.GetName(typeof(EventType), _eventType - 1 - MsgType.Highest).ToUpper();
2020-12-02 18:40:38 +00:00
if (QSBNetworkServer.handlers.Keys.Contains((short)_eventType))
2020-08-22 18:08:25 +01:00
{
2020-08-23 13:56:58 +02:00
DebugLog.ToConsole($"Warning - NetworkServer already contains a handler for EventType {_eventType}", MessageType.Warning);
2020-12-02 18:40:38 +00:00
QSBNetworkServer.handlers.Remove((short)_eventType);
2020-08-22 18:08:25 +01:00
}
2020-12-02 18:40:38 +00:00
QSBNetworkServer.RegisterHandler((short)_eventType, OnServerReceiveMessageHandler);
QSBNetworkManager.singleton.client.RegisterHandler((short)_eventType, OnClientReceiveMessageHandler);
2020-02-21 23:36:07 +01:00
}
public void SendToAll(T message)
{
2020-08-18 22:37:27 +02:00
if (!QSBNetworkManager.Instance.IsReady)
{
return;
}
2020-12-02 18:40:38 +00:00
QSBNetworkServer.SendToAll((short)_eventType, message);
2020-02-21 23:36:07 +01:00
}
public void SendToServer(T message)
{
2020-08-18 22:37:27 +02:00
if (!QSBNetworkManager.Instance.IsReady)
{
return;
}
2020-12-02 18:40:38 +00:00
QSBNetworkManager.singleton.client.Send((short)_eventType, message);
2020-02-21 23:36:07 +01:00
}
2020-12-02 18:40:38 +00:00
private void OnClientReceiveMessageHandler(QSBNetworkMessage netMsg)
2020-02-21 23:36:07 +01:00
{
var message = netMsg.ReadMessage<T>();
OnClientReceiveMessage?.Invoke(message);
}
2020-12-02 18:40:38 +00:00
private void OnServerReceiveMessageHandler(QSBNetworkMessage netMsg)
2020-02-21 23:36:07 +01:00
{
var message = netMsg.ReadMessage<T>();
OnServerReceiveMessage?.Invoke(message);
}
}
}