Engine-Pong/Game/Network/NetworkServer.cs

52 lines
1.5 KiB
C#

using System;
using LiteNetLib.Utils;
using Syntriax.Engine.Network.Abstract;
namespace Syntriax.Engine.Network;
public class NetworkServer : NetworkBase, INetworkCommunicatorServer
{
public string Password { get; private set; } = string.Empty;
public int MaxConnectionCount { get; private set; } = 0;
public int Port { get; private set; } = 8888;
private readonly NetDataWriter netDataWriter = new();
public NetworkServer() : this(8888, 0) { }
public NetworkServer(int port, int maxConnectionCount) : base()
{
MaxConnectionCount = maxConnectionCount;
Port = port;
Listener.ConnectionRequestEvent += request =>
{
if (Manager.ConnectedPeersCount < maxConnectionCount)
request.AcceptIfKey(Password);
else
request.Reject();
};
OnPacketReceived += ServerOnPacketReceived;
}
public void Start(int port, int maxConnectionCount, string? password = null)
{
Password = password ?? string.Empty;
MaxConnectionCount = maxConnectionCount;
Port = port;
Manager.Start(port);
}
public override void Send<T>(NetworkPacket<T> packet)
{
netDataWriter.Reset();
netPacketProcessor.Write(netDataWriter, packet);
Manager.SendToAll(netDataWriter, LiteNetLib.DeliveryMethod.ReliableOrdered);
}
private void ServerOnPacketReceived(INetworkCommunicator sender, object packet)
=> Send((NetworkPacket<object>)packet);
}