2024-07-18 23:07:05 +03:00
|
|
|
using System;
|
2024-07-29 23:01:27 +03:00
|
|
|
using System.Linq;
|
|
|
|
using System.Reflection;
|
2024-07-18 23:07:05 +03:00
|
|
|
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;
|
2024-07-19 21:40:08 +03:00
|
|
|
public int MaxConnectionCount { get; private set; } = 2;
|
2024-07-15 17:00:04 +03:00
|
|
|
public int Port { get; private set; } = 8888;
|
|
|
|
|
2024-07-18 23:07:05 +03:00
|
|
|
private readonly NetDataWriter netDataWriter = new();
|
|
|
|
|
2024-07-19 21:40:08 +03:00
|
|
|
public NetworkServer() : this(8888, 2) { }
|
2024-07-18 23:07:05 +03:00
|
|
|
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)
|
2024-07-29 23:01:27 +03:00
|
|
|
{
|
|
|
|
MethodInfo[] methodInfos = GetType()
|
|
|
|
.GetMethods(BindingFlags.Public | BindingFlags.Instance);
|
|
|
|
|
|
|
|
MethodInfo method = methodInfos
|
|
|
|
.FirstOrDefault(
|
|
|
|
m => m.Name == nameof(Send) && m.IsGenericMethod
|
|
|
|
) ?? throw new Exception();
|
|
|
|
|
|
|
|
Type typeArguments = packet.GetType().GetGenericArguments()[0];
|
|
|
|
|
|
|
|
MethodInfo methodInfo = method.MakeGenericMethod(typeArguments);
|
|
|
|
|
|
|
|
methodInfo.Invoke(this, [packet]);
|
|
|
|
}
|
2024-07-15 17:00:04 +03:00
|
|
|
}
|