61 lines
1.9 KiB
C#
61 lines
1.9 KiB
C#
using System.Linq;
|
|
|
|
using LiteNetLib;
|
|
using LiteNetLib.Utils;
|
|
|
|
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();
|
|
};
|
|
}
|
|
|
|
public void Start(int port, int maxConnectionCount, string? password = null)
|
|
{
|
|
if (!IsInUniverse)
|
|
throw new($"{nameof(NetworkServer)} must be in an universe to start");
|
|
|
|
Password = password ?? string.Empty;
|
|
MaxConnectionCount = maxConnectionCount;
|
|
Port = port;
|
|
|
|
Manager.Start(port);
|
|
}
|
|
|
|
|
|
public void SendToClient(string to, INetworkPacket packet)
|
|
{
|
|
if (packet is not INetSerializable netSerializable)
|
|
throw new($"Packet trying to be sent to the server is not compatible with LiteNetLib");
|
|
|
|
bool isBroadcastToAll = to.CompareTo("*") == 0;
|
|
|
|
netDataWriter.Reset();
|
|
netPacketProcessor.WriteNetSerializable(netDataWriter, ref netSerializable);
|
|
if (isBroadcastToAll)
|
|
Manager.SendToAll(netDataWriter, DeliveryMethod.ReliableOrdered);
|
|
else if (Manager.ConnectedPeerList.FirstOrDefault(p => p.Id.CompareTo(to) == 0) is NetPeer netPeer)
|
|
netPeer.Send(netDataWriter, DeliveryMethod.ReliableOrdered);
|
|
else
|
|
throw new($"Peer {to} couldn't be found.");
|
|
}
|
|
}
|