83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using FlaxEngine;
|
|
using FlaxEngine.Networking;
|
|
using Console = Cabrito.Console;
|
|
using Debug = FlaxEngine.Debug;
|
|
|
|
namespace Game
|
|
{
|
|
public static partial class NetworkManager
|
|
{
|
|
public static uint LocalPlayerClientId { get; private set; } = 0;
|
|
|
|
public static bool ConnectServer()
|
|
{
|
|
client = NetworkPeer.CreatePeer(new NetworkConfig
|
|
{
|
|
NetworkDriver = FlaxEngine.Object.New(typeof(ENetDriver)),
|
|
ConnectionsLimit = MaximumClients,
|
|
MessagePoolSize = 2048,
|
|
MessageSize = MTU,
|
|
Address = ServerAddress == "localhost" ? "127.0.0.1" : ServerAddress,
|
|
Port = ServerPort,
|
|
});
|
|
if (!client.Connect())
|
|
{
|
|
Console.PrintError("Failed to connect to the server.");
|
|
return false;
|
|
}
|
|
|
|
Scripting.FixedUpdate += OnClientUpdate;
|
|
Scripting.Exit += Deinitialize;
|
|
Level.ActorSpawned += OnClientActorSpawned;
|
|
return true;
|
|
}
|
|
|
|
private static void OnClientUpdate()
|
|
{
|
|
using var _ = Utilities.ProfileScope("NetworkManager_OnClientUpdate");
|
|
|
|
while (client.PopEvent(out NetworkEvent networkEvent))
|
|
{
|
|
switch (networkEvent.EventType)
|
|
{
|
|
case NetworkEventType.Connected:
|
|
{
|
|
LocalPlayerClientId = networkEvent.Sender.ConnectionId;
|
|
Console.Print("Connected to server, ConnectionId: " + networkEvent.Sender.ConnectionId);
|
|
break;
|
|
}
|
|
case NetworkEventType.Disconnected:
|
|
{
|
|
Console.Print("Disconnected from server, timeout.");
|
|
LocalPlayerClientId = 0;
|
|
break;
|
|
}
|
|
case NetworkEventType.Timeout:
|
|
{
|
|
Console.Print("Disconnected from server, connection closed.");
|
|
LocalPlayerClientId = 0;
|
|
break;
|
|
}
|
|
case NetworkEventType.Message:
|
|
{
|
|
OnNetworkMessage(networkEvent);
|
|
client.RecycleMessage(networkEvent.Message);
|
|
break;
|
|
}
|
|
default:
|
|
throw new ArgumentOutOfRangeException();
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void OnClientActorSpawned(Actor actor)
|
|
{
|
|
|
|
}
|
|
}
|
|
} |