Skip to content

Commit

Permalink
Simplify port processing at the top level (#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
im-apbecker authored Apr 10, 2024
1 parent f810ffc commit 8e02a1c
Showing 1 changed file with 5 additions and 31 deletions.
36 changes: 5 additions & 31 deletions HKMPServer/HkmpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ public void Initialize(string[] args) {
return;
}

if (string.IsNullOrEmpty(args[0]) || !ParsePort(args[0], out var port)) {
var portArg = args[0];

if (string.IsNullOrEmpty(portArg) || !ushort.TryParse(portArg, out var port)) {
Logger.Info("Invalid port, should be an integer between 0 and 65535");
return;
}
Expand All @@ -47,7 +49,7 @@ public void Initialize(string[] args) {
/// <param name="consoleInputManager">The input manager for command-line input.</param>
/// <param name="consoleLogger">The logging class for logging to console.</param>
private void StartServer(
int port,
ushort port,
ServerSettings serverSettings,
ConsoleInputManager consoleInputManager,
ConsoleLogger consoleLogger
Expand All @@ -60,7 +62,7 @@ ConsoleLogger consoleLogger

var serverManager = new ConsoleServerManager(netServer, serverSettings, packetManager, consoleLogger);
serverManager.Initialize();
serverManager.Start(port);
serverManager.Start((int)port);

// TODO: make an event in ServerManager that we can register for so we know when the server shuts down
consoleInputManager.ConsoleInputEvent += input => {
Expand All @@ -71,33 +73,5 @@ ConsoleLogger consoleLogger
};
consoleInputManager.Start();
}

/// <summary>
/// Try to parse the given input as a networking port.
/// </summary>
/// <param name="input">The string to parse.</param>
/// <param name="port">Will be set to the parsed port if this method returns true, or 0 if the method
/// returns false.</param>
/// <returns>True if the given input was parsed as a valid port, false otherwise.</returns>
private static bool ParsePort(string input, out int port) {
if (!int.TryParse(input, out port)) {
return false;
}

if (!IsValidPort(port)) {
return false;
}

return true;
}

/// <summary>
/// Returns true if the given port is a valid networking port.
/// </summary>
/// <param name="port">The port to check.</param>
/// <returns>True if the port is valid, false otherwise.</returns>
private static bool IsValidPort(int port) {
return port >= 0 && port <= 65535;
}
}
}

0 comments on commit 8e02a1c

Please sign in to comment.