Commands + Server first development release ready (USER: TEST, PASS: 1234) (Serveradress: 185.113.120.99, PORT: 3767)

This commit is contained in:
Tim G. | SnapixLP
2025-06-05 22:58:56 +02:00
parent 838b31cb1f
commit 38a9a72740
15 changed files with 148 additions and 138 deletions

View File

@@ -1,6 +0,0 @@
namespace Server.Commands;
public class ClockCommand
{
}

View File

@@ -0,0 +1,12 @@
namespace Server;
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class CommandAttribute : Attribute
{
public string Name { get; }
public CommandAttribute(string name)
{
Name = name;
}
}

View File

@@ -0,0 +1,10 @@
namespace Server;
using System;
public class CommandException : Exception
{
public CommandException(string message) : base(message)
{
}
}

View File

@@ -0,0 +1,93 @@
using System.Net.Sockets;
using System.Text.Json;
using DX86;
using Library;
namespace Server;
public class CommandLibrary
{
[Command("example")]
public static string ExampleCommand(string[] args, TcpClient? client, TcpServer? socket) =>
$"Example command executed with arguments: {string.Join(", ", args)}";
#region Basic Commands
[Command("help")]
public static string HelpCommand() =>
"Available commands:\n" +
"1. help - Show this help message\n" +
"2. exit - Exit the server\n" +
"3. user - User management\n" +
"4. settings - Server settings\n" +
"5. start - Start the server\n" +
"6. stop - Stop the server\n";
#endregion
#region Client Commands
[Command("login")]
public static string LoginCommand(string[] args, TcpClient? client, TcpServer? socket)
{
if (args.Length < 2)
throw new CommandException("Missing arguments: usage is login <username> <password>");
string username = args[0];
string password = args[1];
if (socket?.LoggedInClients.ContainsKey(client) == true)
throw new CommandException("User already logged in.");
if (username == "TEST" && password == "1234")
{
if (client != null)
{
socket?.LoggedInClients.Add(client, username);
return "success";
}
throw new CommandException("No client connection detected.");
}
throw new CommandException("Invalid username or password.");
}
[Command("logout")]
public static string LogoutCommand(TcpClient? client, TcpServer? socket)
{
if (client != null && socket?.LoggedInClients.ContainsKey(client) == true)
{
socket.LoggedInClients.Remove(client);
return "success";
}
throw new CommandException("No client provided or not logged in");
}
[Command("getSelfUser")]
public static string GetSelfUserCommand(TcpClient? client, TcpServer? socket)
{
if (client == null || socket == null)
throw new CommandException("No client connection detected.");
if (socket.LoggedInClients.TryGetValue(client, out var username))
{
Employee returnEmployee = new Employee(username);
string jsonEmployee = JsonSerializer.Serialize(returnEmployee);
return jsonEmployee;
}
throw new CommandException("User not logged in.");
}
#endregion
#region Administration Commands
[Command("get")]
public static string GetCommand(string[] args, TcpClient? client, TcpServer? socket) =>
$"not implemented yet, args: {string.Join(", ", args)}";
#endregion
}

View File

@@ -0,0 +1,118 @@
using System.Net.Sockets;
using System.Reflection;
using System.Text.Json;
using DX86;
namespace Server;
public class CommandManager
{
private readonly Dictionary<string, MethodInfo> _commands = new();
public CommandManager()
{
LoadCommands();
}
private void LoadCommands()
{
var methods = Assembly.GetExecutingAssembly()
.GetTypes()
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Static))
.Where(m => m.GetCustomAttribute<CommandAttribute>() != null);
foreach (var method in methods)
{
var attr = method.GetCustomAttribute<CommandAttribute>()!;
_commands[attr.Name.ToLower()] = method;
Program.messageSender.Log($"[COMMANDMANAGER] Registered command: {attr.Name}");
}
}
public void ExecuteCommand(string executor,
TcpClient? client = null,
TcpServer? clientSocket = null,
string cid = "",
params string[] args)
{
// — ensure args is never null —
args ??= Array.Empty<string>();
if (_commands.TryGetValue(executor.ToLower(), out var method))
{
try
{
var parameters = method.GetParameters();
var arguments = new object?[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
var param = parameters[i];
if (param.ParameterType == typeof(string[]))
arguments[i] = args;
else if (param.ParameterType == typeof(TcpClient))
arguments[i] = client;
else if (param.ParameterType == typeof(TcpServer))
arguments[i] = clientSocket;
else
{
Program.messageSender.Warn(
$"[COMMANDMANAGER] Unknown parameter type '{param.ParameterType.Name}' in '{executor}'. Defaulting that argument to null."
);
arguments[i] = null;
}
}
Program.messageSender.Debug($"[COMMANDMANAGER] Executing command '{executor}'…");
var rawResult = method.Invoke(null, arguments); // invoke the static command method
string result = rawResult?.ToString() ?? "";
// **Log the returned string before sending**
Program.messageSender.Debug($"[COMMANDMANAGER] Command '{executor}' returned: \"{result}\"");
var returnMessage = new Library.Server.JsonResponse
{
Id = cid,
Response = result
};
var sendClientMessage = JsonSerializer.Serialize(returnMessage);
clientSocket?.SendMessageAsync(client, sendClientMessage + "\n");
Program.messageSender.Debug($"[COMMANDMANAGER] Response sent to client.");
}
// If your command threw a CommandException, catch it here:
catch (TargetInvocationException ex) when (ex.InnerException is CommandException cmdEx)
{
Program.messageSender.Warn($"[COMMANDMANAGER] Command '{executor}' failed: {cmdEx.Message}");
var returnMessage = new Library.Server.JsonResponse
{
Id = cid,
Response = $"Error: {cmdEx.Message}"
};
var sendClientMessage = JsonSerializer.Serialize(returnMessage);
clientSocket?.SendMessageAsync(client, sendClientMessage + "\n");
}
// Any other exception inside the invoked method
catch (TargetInvocationException ex)
{
var actualError = ex.InnerException?.Message ?? ex.Message;
Program.messageSender.Error(
$"[COMMANDMANAGER] Unexpected error in command '{executor}': {actualError}"
);
Program.messageSender.Debug(
$"[COMMANDMANAGER] Stack Trace: {ex.InnerException?.StackTrace ?? ex.StackTrace}"
);
}
// Anything else thrown before or during Invoke()
catch (Exception ex)
{
Program.messageSender.Error($"[COMMANDMANAGER] Failed to invoke command '{executor}': {ex.Message}");
}
}
else
{
Program.messageSender.Warn($"[COMMANDMANAGER] Unknown command '{executor}' received.");
}
}
}

View File

@@ -1,6 +0,0 @@
namespace Server.Commands;
public class GetCommand
{
}

View File

@@ -1,26 +0,0 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public class HelpCommand : ICommand
{
public string Executor { get; }
public HelpCommand()
{
Executor = "help";
}
public string Exec(string[] args, TcpClient? client = null, TcpServer? clientSocket = null)
{
return
"Available commands:\n" +
"1. help - Show this help message\n" +
"2. exit - Exit the server\n" +
"3. user - User management\n" +
"4. settings - Server settings\n" +
"5. start - Start the server\n" +
"6. stop - Stop the server\n"
;
}
}

View File

@@ -1,10 +0,0 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public interface ICommand
{
string Executor { get; }
public string Exec(string[] args, TcpClient? client, TcpServer? clientSocket);
}

View File

@@ -1,34 +0,0 @@
using System.Net.Sockets;
using DX86;
using MySqlX.XDevAPI;
namespace Server.Commands;
public class LoginCommand : ICommand
{
public string Executor { get; }
public LoginCommand()
{
Executor = "login";
}
public string Exec(string[] args, TcpClient? client, TcpServer? clientSocket)
{
if (args[0] == "test" && args[1] == "test")
{
if (client != null)
{
//clientSocket?.SendMessageAsync(client, "Login successful");
clientSocket?.LoggedInClients.Add(client, "test");
return "Login successful";
}
}
else
{
if (client != null) return "Invalid credentials";
}
return "No client provided or invalid credentials";
}
}

View File

@@ -1,30 +0,0 @@
using System.Net.Sockets;
using DX86;
namespace Server.Commands;
public class LogoutCommand : ICommand
{
public string Executor { get; }
public LogoutCommand()
{
Executor = "logout";
}
public string Exec(string[] args, TcpClient? client = null, TcpServer? clientSocket = null)
{
if (clientSocket == null && client == null)
return "Please provide a valid client or clientSocket.";
if (client != null && clientSocket != null && clientSocket.LoggedInClients.ContainsKey(client))
{
clientSocket.LoggedInClients.Remove(client);
//clientSocket.SendMessageAsync(client, "Success");
return "Logout successful.";
}
else
{
//clientSocket?.SendMessageAsync(client, "Logout failed. You are not logged in.");
return "Logout failed. You are not logged in.";
}
}
}