Build heartbeat chain
This commit is contained in:
1 parent
909718d8d5
commit
f946ebef1e
5 files changed
+173
-122
No files matched your search
@@ -1,7 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Numerics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Mistox.ResevedPackets;
|
||||
|
||||
@@ -13,15 +16,21 @@ namespace Mistox.Client {
|
||||
public string UserName { get; private set; } = ""; // My UserName
|
||||
public bool Alive { get; set; } = true; // Is the server running
|
||||
public bool isAuthenticated { get; private set; } = false; // Is the server authenticated
|
||||
public ConcurrentDictionary<IPEndPoint, mUDPClient> clientConnections { get; private set; } // UserName, Connection
|
||||
public ConcurrentDictionary<IPEndPoint, mUDPClient> clientConnections { get; private set; } = new(); // UserName, Connection
|
||||
public Vector3 Position { get; set; } = new Vector3(0, 0, 0); // My world position
|
||||
public float MaxNetworkRenderDistance { get; private set; } = 0; // The distance for connections
|
||||
|
||||
public mTCPClient ServerConnection {get; private set; } // Global TCP Server Connection
|
||||
public UdpClient ClientSocket { get; private set; } // Global UDP Sender
|
||||
public UDPReceiver UdpReceiver { get; private set; } // Global UDP Receiver
|
||||
|
||||
private readonly string ConnectionKey = ""; // Server Connection Key
|
||||
|
||||
private readonly int Port = 0; // The port of the connected socket
|
||||
private readonly int HeartbeatInterval = 5000; // How often should we heartbeat
|
||||
|
||||
public MistoxClient(string userName, string connectionKey, IPEndPoint Server) {
|
||||
// Create and listen on UDP
|
||||
Port = Server.Port;
|
||||
ClientSocket = new UdpClient( Server.Port );
|
||||
UdpReceiver = new UDPReceiver( this );
|
||||
UserName = userName;
|
||||
@@ -33,15 +42,79 @@ namespace Mistox.Client {
|
||||
ServerConnection = new mTCPClient( this, Server );
|
||||
Console.WriteLine( "Connected to the server sucessfully" );
|
||||
Alive = true;
|
||||
} catch( Exception e ) {
|
||||
} catch ( Exception e ) {
|
||||
Console.WriteLine( "An error has occured with the connection to the server. Error { " );
|
||||
Console.WriteLine( e.ToString() );
|
||||
Console.WriteLine( "}" );
|
||||
Alive = false;
|
||||
}
|
||||
|
||||
// Start the heartbeat
|
||||
_ = RunAsync(Heartbeat);
|
||||
}
|
||||
|
||||
public async Task TryAuth() {
|
||||
async Task RunAsync(Func<Task> work) {
|
||||
try{
|
||||
await work();
|
||||
} catch (Exception ex) {
|
||||
Console.WriteLine($"Error during background packet processing: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
// Heartbeat
|
||||
/////////////////////////////
|
||||
|
||||
async Task Heartbeat() {
|
||||
while (Alive) {
|
||||
await SendServer(new HeartbeatPacket {
|
||||
Position = Position
|
||||
});
|
||||
Thread.Sleep(HeartbeatInterval);
|
||||
}
|
||||
}
|
||||
|
||||
void HeartbeatReceived(HeartbeatPacket packet) {
|
||||
// Build a HashSet of server IP addresses for O(1) removal checks
|
||||
var activeIps = new HashSet<IPAddress>(packet.ServerList.Count);
|
||||
for (int i = 0; i < packet.ServerList.Count; i++) {
|
||||
activeIps.Add(packet.ServerList[i].IpAddress);
|
||||
}
|
||||
|
||||
// Add users that joined
|
||||
foreach (UserTableObject cur in packet.ServerList) {
|
||||
IPEndPoint remoteHost = new IPEndPoint(cur.IpAddress, Port);
|
||||
if (!clientConnections.ContainsKey(remoteHost)) {
|
||||
mUDPClient newConnection = new mUDPClient(this, remoteHost);
|
||||
clientConnections[remoteHost] = newConnection;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove users that left
|
||||
foreach (IPEndPoint key in clientConnections.Keys) {
|
||||
if (!activeIps.Contains(key.Address)) {
|
||||
clientConnections.TryRemove(key, out _);
|
||||
}
|
||||
}
|
||||
|
||||
// Update distance status
|
||||
float maxDistanceSq = MaxNetworkRenderDistance * MaxNetworkRenderDistance;
|
||||
foreach (mUDPClient cur in clientConnections.Values) {
|
||||
float dx = Position.X - cur.Position.X;
|
||||
float dy = Position.Y - cur.Position.Y;
|
||||
float dz = Position.Z - cur.Position.Z;
|
||||
|
||||
// Fixed bug (dz * dz instead of dz + dz) & avoided Sqrt
|
||||
float distanceSq = (dx * dx) + (dy * dy) + (dz * dz);
|
||||
cur.WithinRange = distanceSq < maxDistanceSq;
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
// Auth
|
||||
/////////////////////////////
|
||||
|
||||
async Task TryAuth() {
|
||||
Console.WriteLine("Attempting to authenticate against the server...");
|
||||
await ServerConnection.Send(new UserAuthPacket {
|
||||
UserName = UserName,
|
||||
@@ -49,71 +122,18 @@ namespace Mistox.Client {
|
||||
});
|
||||
}
|
||||
|
||||
public async Task CheckAuthStatus(UserAuthPacket packet) {
|
||||
async Task CheckAuthStatus(UserAuthPacket packet) {
|
||||
if (packet.AuthSuccessful == 1) {
|
||||
isAuthenticated = true;
|
||||
}
|
||||
ServerName = packet.ServerName;
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
// Receive Methods
|
||||
/////////////////////////////
|
||||
|
||||
public void UserConnected(UserConnectedPacket packet) {
|
||||
IPEndPoint remoteUser = new IPEndPoint(packet.ClientIPAddress, packet.ClientPort);
|
||||
mUDPClient user = new mUDPClient(this, remoteUser) {
|
||||
UserName = packet.UserName
|
||||
};
|
||||
clientConnections[remoteUser] = user;
|
||||
InvokeOnUserConnected(user);
|
||||
}
|
||||
|
||||
public void UserDisconnected(UserDisconnectedPacket packet) {
|
||||
mUDPClient client = null;
|
||||
foreach(mUDPClient cur in clientConnections.Values) {
|
||||
if (cur.UserName.ToLower() == packet.UserName.ToLower()) {
|
||||
client = cur;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (client != null) {
|
||||
InvokeOnUserDisconnected( client );
|
||||
client.Alive = false;
|
||||
client.Dispose();
|
||||
clientConnections[client._remoteHost] = null;
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
// Events
|
||||
/////////////////////////////
|
||||
|
||||
public event Action<dynamic> onDataReceived;
|
||||
public void InvokeOnReceived(dynamic DataPacket, mUDPClient remote = null){
|
||||
switch (DataPacket as object) {
|
||||
case UserConnectedPacket packet:
|
||||
UserConnected(packet);
|
||||
break;
|
||||
case UserDisconnectedPacket packet:
|
||||
UserDisconnected(packet);
|
||||
break;
|
||||
case UserAuthPacket packet:
|
||||
Task.Run(async () => {
|
||||
try {
|
||||
await CheckAuthStatus(packet);
|
||||
} catch {}
|
||||
});
|
||||
break;
|
||||
case null:
|
||||
Console.WriteLine("Received a null packet.");
|
||||
break;
|
||||
default:
|
||||
onDataReceived?.Invoke(DataPacket);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// When (self) connects to the server
|
||||
public event Action onServerConnected;
|
||||
public void InvokeOnServerConnected(){
|
||||
Alive = true;
|
||||
@@ -125,26 +145,67 @@ namespace Mistox.Client {
|
||||
onServerConnected?.Invoke();
|
||||
}
|
||||
|
||||
// When any user connects to the server (self) hasn't seen yet
|
||||
public event Action<string> onUserJoined;
|
||||
public void InvokeOnUserJoined(string UserName){
|
||||
onUserJoined?.Invoke(UserName);
|
||||
}
|
||||
|
||||
// When user is within range of (self) and network rendering starts
|
||||
public event Action<mUDPClient> onUserConnected;
|
||||
public void InvokeOnUserConnected(mUDPClient ConnectedUser){
|
||||
onUserConnected?.Invoke(ConnectedUser);
|
||||
}
|
||||
|
||||
// When generic data is received
|
||||
public event Action<dynamic> onDataReceived;
|
||||
public void InvokeOnReceived(dynamic DataPacket, mUDPClient remote = null){
|
||||
switch (DataPacket as object) {
|
||||
case HeartbeatPacket packet:
|
||||
HeartbeatReceived(packet);
|
||||
break;
|
||||
case UserAuthPacket packet:
|
||||
_ = RunAsync(async () => {
|
||||
await CheckAuthStatus(packet);
|
||||
});
|
||||
break;
|
||||
case null:
|
||||
Console.WriteLine("Received a null packet.");
|
||||
break;
|
||||
default:
|
||||
onDataReceived?.Invoke(DataPacket);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// When user is no longer in range of (self) and network rendering stops
|
||||
public event Action<mUDPClient> onUserDisconnected;
|
||||
public void InvokeOnUserDisconnected(mUDPClient DisconnectedUser){
|
||||
onUserDisconnected?.Invoke(DisconnectedUser);
|
||||
}
|
||||
|
||||
// When any user disconnects from the server that isn't (self)
|
||||
public event Action<string> onUserLeft;
|
||||
public void InvokeOnUserLeft(string UserName){
|
||||
onUserLeft?.Invoke(UserName);
|
||||
}
|
||||
|
||||
// When (self) disconnects to the server
|
||||
public event Action onServerDisconnected;
|
||||
public void InvokeOnServerDisconnected(){
|
||||
Alive = false;
|
||||
onServerDisconnected?.Invoke();
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
// Send Methods
|
||||
/////////////////////////////
|
||||
|
||||
public async Task SendAllClients<Packet>(Packet data) {
|
||||
public async Task SendAllClientsInRange<Packet>(Packet data) {
|
||||
foreach( mUDPClient cur in clientConnections.Values ){
|
||||
await cur.Send( data );
|
||||
if (cur.WithinRange) {
|
||||
await cur.Send( data );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user