feat: engine data type packers
This commit is contained in:
61
Shared/Network/LiteNetLib/LiteNetLibServer.cs
Normal file
61
Shared/Network/LiteNetLib/LiteNetLibServer.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System.Linq;
|
||||
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
|
||||
namespace Syntriax.Engine.Network;
|
||||
|
||||
public class LiteNetLibServer : LiteNetLibCommunicatorBase, INetworkCommunicatorServer
|
||||
{
|
||||
public string Password { get; private set; } = string.Empty;
|
||||
public int MaxConnectionCount { get; private set; } = 2;
|
||||
public int Port { get; private set; } = 8888;
|
||||
|
||||
private readonly NetDataWriter netDataWriter = new();
|
||||
|
||||
public LiteNetLibServer() : this(8888, 2) { }
|
||||
public LiteNetLibServer(int port, int maxConnectionCount) : base()
|
||||
{
|
||||
MaxConnectionCount = maxConnectionCount;
|
||||
Port = port;
|
||||
|
||||
Listener.ConnectionRequestEvent += request =>
|
||||
{
|
||||
if (Manager.ConnectedPeersCount < maxConnectionCount)
|
||||
request.AcceptIfKey(Password);
|
||||
else
|
||||
request.Reject();
|
||||
};
|
||||
}
|
||||
|
||||
public INetworkCommunicatorServer Start(int port, int maxConnectionCount, string? password = null)
|
||||
{
|
||||
if (!IsInUniverse)
|
||||
throw new($"{nameof(LiteNetLibServer)} must be in an universe to start");
|
||||
|
||||
Password = password ?? string.Empty;
|
||||
MaxConnectionCount = maxConnectionCount;
|
||||
Port = port;
|
||||
|
||||
Manager.Start(port);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public INetworkCommunicatorServer SendToClient<T>(string to, T packet) where T : class, new()
|
||||
{
|
||||
bool isBroadcastToAll = to.CompareTo("*") == 0;
|
||||
|
||||
netDataWriter.Reset();
|
||||
netPacketProcessor.Write(netDataWriter, packet);
|
||||
if (isBroadcastToAll)
|
||||
Manager.SendToAll(netDataWriter, DeliveryMethod.ReliableOrdered);
|
||||
else if (Manager.ConnectedPeerList.FirstOrDefault(p => p.Id.ToString().CompareTo(to) == 0) is NetPeer netPeer)
|
||||
netPeer.Send(netDataWriter, DeliveryMethod.ReliableOrdered);
|
||||
else
|
||||
throw new($"Peer {to} couldn't be found.");
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user