Engine-Pong/Game/Network/NetworkServer.cs

50 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using LiteNetLib;
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Abstract;
namespace Pong.Network;
public class NetworkServer : BehaviourOverride, INetworkServer
{
public string Password { get; private set; } = string.Empty;
public int MaxConnectionCount { get; private set; } = 0;
public int Port { get; private set; } = 8888;
public EventBasedNetListener Listener { get; private set; } = null!;
public NetManager Manager { get; private set; } = null!;
public NetworkServer()
{
Priority = 10;
Listener = new EventBasedNetListener();
Manager = new NetManager(Listener);
Listener.ConnectionRequestEvent += request =>
{
if (Manager.ConnectedPeersCount < MaxConnectionCount)
request.AcceptIfKey(Password);
else
request.Reject();
};
}
public void Start(int port, int maxConnectionCount, string? password = null)
{
Password = password ?? string.Empty;
MaxConnectionCount = maxConnectionCount;
Port = port;
Manager.Start(port);
}
public void PollEvents() => Manager.PollEvents();
public void Stop() => Manager.Stop();
protected override void OnUpdate() => PollEvents();
protected override void OnFinalize() => Stop();
}