Engine-Pong/Game/Network/NetworkBase.cs

74 lines
2.0 KiB
C#
Raw Normal View History

2024-02-02 12:42:59 +03:00
using System;
using System.Collections.Generic;
using LiteNetLib;
using LiteNetLib.Utils;
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Abstract;
namespace Pong.Network;
public abstract class NetworkBase : BehaviourOverride, INetworkCommunicator
{
public EventBasedNetListener Listener { get; private set; } = null!;
public NetManager Manager { get; private set; } = null!;
public NetworkBase()
{
Priority = 10;
Listener = new EventBasedNetListener();
Manager = new NetManager(Listener);
Listener.NetworkReceiveEvent += NetworkReceiveEvent;
}
public void PollEvents() => Manager.PollEvents();
public void Stop() => Manager.Stop();
protected override void OnUpdate() => PollEvents();
protected override void OnFinalize() => Stop();
private Dictionary<string, Action<NetPacketReader>> callbacks = new(32);
private void NetworkReceiveEvent(NetPeer peer, NetPacketReader reader, byte channel, DeliveryMethod deliveryMethod)
{
if (callbacks.TryGetValue(reader.GetString(), out var action))
action?.Invoke(reader);
reader.Recycle();
}
public void RegisterEntityListener(IEntity entity, Action<NetPacketReader> onDataReceived)
{
if (callbacks.ContainsKey(entity.Id))
return;
callbacks.Add(entity.Id, onDataReceived);
entity.OnIdChanged += OnEntityIdChanged;
}
public void UnregisterEntityListener(IEntity entity)
{
if (!callbacks.Remove(entity.Id))
return;
entity.OnIdChanged -= OnEntityIdChanged;
}
public NetDataWriter GetEntityWriter(IEntity entity)
{
NetDataWriter netDataWriter = new();
netDataWriter.Put(entity.Id);
return netDataWriter;
}
private void OnEntityIdChanged(IEntity entity, string previousId)
{
var action = callbacks[previousId];
callbacks.Remove(previousId);
callbacks.Add(entity.Id, action);
}
}