Files
GoakeFlax/Source/Game/Network/NetworkManager_Client.cs
2022-05-02 20:34:42 +03:00

93 lines
3.2 KiB
C#

using System;
using System.Diagnostics;
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 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 eventData))
{
switch (eventData.EventType)
{
case NetworkEventType.Connected:
{
LocalPlayerClientId = eventData.Sender.ConnectionId;
Console.Print("Connected to server, ConnectionId: " + eventData.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:
{
// Read the message contents
var message = eventData.Message;
var messageData = message.ReadString();
Console.Print($"Received message from Client({eventData.Sender.ConnectionId}): {messageData}");
// Send hello message to the client back
{
var sendmessage = client.BeginSendMessage();
sendmessage.WriteString($"Hello, Server({eventData.Sender.ConnectionId})!");
client.EndSendMessage(NetworkChannelType.Reliable, sendmessage);
}
client.RecycleMessage(message);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
}
private static void OnClientActorSpawned(Actor actor)
{
}
}
}