68 lines
2.0 KiB
C#
68 lines
2.0 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
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; } = 2;
|
|
public int Port { get; private set; } = 8888;
|
|
|
|
private readonly NetDataWriter netDataWriter = new();
|
|
|
|
public NetworkServer() : this(8888, 2) { }
|
|
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)
|
|
{
|
|
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]);
|
|
}
|
|
}
|