2020-02-21 23:36:07 +01:00
|
|
|
|
using System;
|
|
|
|
|
using UnityEngine.Networking;
|
|
|
|
|
|
|
|
|
|
namespace QSB.Messaging
|
|
|
|
|
{
|
|
|
|
|
// Extend this to create new message handlers.
|
|
|
|
|
public class MessageHandler<T> where T : QSBMessage, new()
|
|
|
|
|
{
|
|
|
|
|
public event Action<T> OnClientReceiveMessage;
|
|
|
|
|
public event Action<T> OnServerReceiveMessage;
|
|
|
|
|
|
2020-08-09 11:11:45 +02:00
|
|
|
|
private readonly MessageType _messageType;
|
|
|
|
|
|
|
|
|
|
public MessageHandler(MessageType messageType)
|
2020-03-13 20:44:32 +01:00
|
|
|
|
{
|
2020-08-09 12:19:51 +01:00
|
|
|
|
_messageType = messageType + 1 + MsgType.Highest;
|
2020-03-13 20:44:32 +01:00
|
|
|
|
if (QSBNetworkManager.IsReady)
|
|
|
|
|
{
|
|
|
|
|
Init();
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
QSBNetworkManager.OnNetworkManagerReady.AddListener(Init);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void Init()
|
2020-02-21 23:36:07 +01:00
|
|
|
|
{
|
2020-08-09 11:11:45 +02:00
|
|
|
|
NetworkServer.RegisterHandler((short)_messageType, OnServerReceiveMessageHandler);
|
|
|
|
|
NetworkManager.singleton.client.RegisterHandler((short)_messageType, OnClientReceiveMessageHandler);
|
2020-02-21 23:36:07 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void SendToAll(T message)
|
|
|
|
|
{
|
2020-03-13 20:44:32 +01:00
|
|
|
|
if (!QSBNetworkManager.IsReady)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
2020-08-09 11:11:45 +02:00
|
|
|
|
NetworkServer.SendToAll((short)_messageType, message);
|
2020-02-21 23:36:07 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void SendToServer(T message)
|
|
|
|
|
{
|
2020-03-13 20:44:32 +01:00
|
|
|
|
if (!QSBNetworkManager.IsReady)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
2020-08-09 11:11:45 +02:00
|
|
|
|
NetworkManager.singleton.client.Send((short)_messageType, message);
|
2020-02-21 23:36:07 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnClientReceiveMessageHandler(NetworkMessage netMsg)
|
|
|
|
|
{
|
|
|
|
|
var message = netMsg.ReadMessage<T>();
|
|
|
|
|
OnClientReceiveMessage?.Invoke(message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnServerReceiveMessageHandler(NetworkMessage netMsg)
|
|
|
|
|
{
|
|
|
|
|
var message = netMsg.ReadMessage<T>();
|
|
|
|
|
OnServerReceiveMessage?.Invoke(message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|