feat: NetworkClient & Server to IBehaviour

This commit is contained in:
Syntriax 2024-02-02 12:27:34 +03:00
parent d4c57c0153
commit ef8b04648c
2 changed files with 38 additions and 15 deletions

View File

@ -1,21 +1,34 @@
using System;
using System.Collections.Generic;
using LiteNetLib;
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Abstract;
namespace Pong.Network;
public class NetworkClient
public class NetworkClient : BehaviourOverride, INetworkClient
{
public readonly EventBasedNetListener Listener = null!;
public readonly NetManager Client = null!;
public EventBasedNetListener Listener { get; private set; } = null!;
public NetManager Manager { get; private set; } = null!;
public NetworkClient()
{
Priority = 10;
Listener = new EventBasedNetListener();
Client = new NetManager(Listener);
Manager = new NetManager(Listener);
}
public void Connect(string address, int port, string? password = null)
=> Client.Connect(address, port, password ?? string.Empty);
{
Manager.Start();
Manager.Connect(address, port, password ?? string.Empty);
}
public void PollEvents() => Client.PollEvents();
public void Stop() => Client.Stop();
public void PollEvents() => Manager.PollEvents();
public void Stop() => Manager.Stop();
protected override void OnUpdate() => PollEvents();
protected override void OnFinalize() => Stop();
}

View File

@ -1,24 +1,31 @@
using System;
using System.Collections.Generic;
using LiteNetLib;
using Syntriax.Engine.Core;
using Syntriax.Engine.Core.Abstract;
namespace Pong.Network;
public class NetworkServer
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 readonly EventBasedNetListener Listener = null!;
public readonly NetManager Server = null!;
public EventBasedNetListener Listener { get; private set; } = null!;
public NetManager Manager { get; private set; } = null!;
public NetworkServer()
{
Priority = 10;
Listener = new EventBasedNetListener();
Server = new NetManager(Listener);
Manager = new NetManager(Listener);
Listener.ConnectionRequestEvent += request =>
{
if (Server.ConnectedPeersCount < MaxConnectionCount)
if (Manager.ConnectedPeersCount < MaxConnectionCount)
request.AcceptIfKey(Password);
else
request.Reject();
@ -31,9 +38,12 @@ public class NetworkServer
MaxConnectionCount = maxConnectionCount;
Port = port;
Server.Start(port);
Manager.Start(port);
}
public void PollEvents() => Server.PollEvents();
public void Stop() => Server.Stop();
public void PollEvents() => Manager.PollEvents();
public void Stop() => Manager.Stop();
protected override void OnUpdate() => PollEvents();
protected override void OnFinalize() => Stop();
}