Skip to content

Commit 3a89eb4

Browse files
committed
fix: 无法记住前端选项
1 parent cb06521 commit 3a89eb4

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

MaiChartManager/ServerManager.cs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
using System.Net;
2+
using System.Net.NetworkInformation;
3+
using System.Net.Sockets;
24
using System.Security.Cryptography.X509Certificates;
35
using System.Text.Json.Serialization;
46
using System.Windows.Forms;
@@ -60,6 +62,33 @@ private static X509Certificate2 GetCert()
6062
return cert;
6163
}
6264

65+
private static bool IsPortAvailable(int port)
66+
{
67+
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
68+
var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
69+
Console.WriteLine(string.Join(", ", tcpConnInfoArray.Select(tcpi => tcpi.LocalEndPoint.Port.ToString())));
70+
foreach (var tcpi in tcpConnInfoArray)
71+
{
72+
if (tcpi.LocalEndPoint.Port == port)
73+
{
74+
return false;
75+
}
76+
}
77+
78+
return true;
79+
}
80+
81+
private static int GetAvailablePort()
82+
{
83+
var port = 49182;
84+
while (!IsPortAvailable(port))
85+
{
86+
port++;
87+
}
88+
89+
return port;
90+
}
91+
6392
public static void StartApp(bool export, Action? onStart = null)
6493
{
6594
var builder = WebApplication.CreateBuilder();
@@ -92,7 +121,7 @@ public static void StartApp(bool export, Action? onStart = null)
92121
# if !DEBUG
93122
builder.WebHost.ConfigureKestrel((context, serverOptions) =>
94123
{
95-
serverOptions.Listen(IPAddress.Loopback, 0);
124+
serverOptions.Listen(IPAddress.Loopback, GetAvailablePort());
96125
if (export)
97126
{
98127
serverOptions.Listen(IPAddress.Any, 5001, listenOptions =>

0 commit comments

Comments
 (0)