Engine-Pong/Game/Network/NetworkServer.cs

52 lines
1.5 KiB
C#
Raw Normal View History

2024-07-18 23:07:05 +03:00
using System;
using LiteNetLib.Utils;
2024-07-15 17:00:04 +03:00
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;
2024-07-18 23:07:05 +03:00
private readonly NetDataWriter netDataWriter = new();
public NetworkServer() : this(8888, 0) { }
public NetworkServer(int port, int maxConnectionCount) : base()
2024-07-15 17:00:04 +03:00
{
2024-07-18 23:07:05 +03:00
MaxConnectionCount = maxConnectionCount;
Port = port;
2024-07-15 17:00:04 +03:00
Listener.ConnectionRequestEvent += request =>
{
2024-07-18 23:07:05 +03:00
if (Manager.ConnectedPeersCount < maxConnectionCount)
2024-07-15 17:00:04 +03:00
request.AcceptIfKey(Password);
else
request.Reject();
};
2024-07-18 23:07:05 +03:00
OnPacketReceived += ServerOnPacketReceived;
2024-07-15 17:00:04 +03:00
}
public void Start(int port, int maxConnectionCount, string? password = null)
{
Password = password ?? string.Empty;
MaxConnectionCount = maxConnectionCount;
Port = port;
Manager.Start(port);
}
2024-07-18 23:07:05 +03:00
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);
2024-07-15 17:00:04 +03:00
}