naps2/NAPS2.Escl.Server/PortFinder.cs
Ben Olden-Cooligan 29b3c57207 Escl: Fix port handling and server restarts
Ports are now static per SharedDevice where possible, falling back to random ports if an error occurs.
2023-12-02 22:57:30 -08:00

43 lines
1.1 KiB
C#

namespace NAPS2.Escl.Server;
internal static class PortFinder
{
private const int MAX_PORT_TRIES = 5;
private const int RANDOM_PORT_MIN = 10001;
private const int RANDOM_PORT_MAX = 19999;
public static async Task RunWithSpecifiedOrRandomPort(int defaultPort, Func<int, Task> portTaskFunc,
CancellationToken cancelToken)
{
int port = defaultPort;
int retries = 0;
var random = new Random();
if (port == 0)
{
port = RandomPort(random);
}
while (true)
{
try
{
await portTaskFunc(port);
break;
}
catch (Exception)
{
if (cancelToken.IsCancellationRequested)
{
break;
}
retries++;
port = RandomPort(random);
if (retries > MAX_PORT_TRIES)
{
throw;
}
}
}
}
private static int RandomPort(Random random) => random.Next(RANDOM_PORT_MIN, RANDOM_PORT_MAX + 1);
}