Engine-Pong/Game/Network/NetworkServer.cs

50 lines
1.3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2024-02-01 23:38:39 +03:00
using LiteNetLib;
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Abstract;
2024-02-02 12:04:53 +03:00
namespace Pong.Network;
2024-02-01 23:38:39 +03:00
public class NetworkServer : BehaviourOverride, INetworkServer
2024-02-01 23:38:39 +03:00
{
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!;
2024-02-01 23:38:39 +03:00
public NetworkServer()
{
Priority = 10;
2024-02-01 23:38:39 +03:00
Listener = new EventBasedNetListener();
Manager = new NetManager(Listener);
2024-02-01 23:38:39 +03:00
Listener.ConnectionRequestEvent += request =>
{
if (Manager.ConnectedPeersCount < MaxConnectionCount)
2024-02-01 23:38:39 +03:00
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);
2024-02-01 23:38:39 +03:00
}
public void PollEvents() => Manager.PollEvents();
public void Stop() => Manager.Stop();
protected override void OnUpdate() => PollEvents();
protected override void OnFinalize() => Stop();
2024-02-01 23:38:39 +03:00
}