Program.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using HTEX.ScreenClient.Services;
  2. using System.Diagnostics;
  3. using System.Management;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Runtime.InteropServices;
  7. using System.Text.RegularExpressions;
  8. using TEAMModelOS.SDK.DI.Device;
  9. using Serilog;
  10. namespace HTEX.ScreenClient
  11. {
  12. public class Program
  13. {
  14. public static void Main(string[] args)
  15. {
  16. var builder = WebApplication.CreateBuilder(args);
  17. builder.WebHost.UseKestrel(options =>
  18. {
  19. // options.ListenAnyIP(CheckOrNewPort(1883), options => {/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
  20. options.ListenAnyIP(CheckOrNewPort(5000), options => {/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
  21. });
  22. //写在端口配置之前,并且在用到的DI之前。否则会导致DI注入失败
  23. Log.Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss.fff zzz} [{Level:u3}] ({ThreadId}) {Message}{NewLine}{Exception}")
  24. .WriteTo.File("logs/log-.log", rollingInterval: RollingInterval.Day).CreateLogger();
  25. builder.Host.UseSerilog();
  26. builder.Services.AddControllers();
  27. builder.Services.AddHttpClient();
  28. builder.Services.AddHttpContextAccessor();
  29. builder.Services.AddHostedService<SignalRScreenClientHub>();
  30. builder.Services.AddSingleton<CoreDevice>();
  31. var app = builder.Build();
  32. app.UseHttpsRedirection();
  33. app.UseAuthorization();
  34. app.MapControllers();
  35. app.Run();
  36. }
  37. /// <summary>
  38. /// 检测端口是否可用,如果不可用,则递归调用本方法,直到可用为止
  39. /// </summary>
  40. /// <param name="port"></param>
  41. /// <returns></returns>
  42. public static int CheckOrNewPort(int port)
  43. {
  44. if (IsPortAvailable(port))
  45. {
  46. return port;
  47. }
  48. else
  49. {
  50. return CheckOrNewPort(port + 1);
  51. }
  52. }
  53. /// <summary>
  54. /// 探测端口是否可用
  55. /// </summary>
  56. /// <param name="port"></param>
  57. /// <returns></returns>
  58. public static bool IsPortAvailable(int port)
  59. {
  60. bool isPortAvailable = false;
  61. IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); // 本地地址
  62. try
  63. {
  64. using (Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
  65. {
  66. // 尝试连接到指定的IP地址和端口
  67. IAsyncResult result = socket.BeginConnect(ipAddress, port, null, null);
  68. // 等待连接尝试完成(这里简单地使用Socket的ConnectTimeout,但更常见的做法是使用超时等待或异步回调)
  69. bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1), true);
  70. if (success)
  71. {
  72. // 如果连接成功,则端口被占用
  73. socket.EndConnect(result);
  74. isPortAvailable = false;
  75. // 可选:如果需要,可以在这里关闭连接
  76. //socket.Shutdown(SocketShutdown.Both);
  77. //socket.Close();
  78. }
  79. else
  80. {
  81. isPortAvailable = true;
  82. }
  83. }
  84. }
  85. catch (SocketException ex)
  86. {
  87. Console.WriteLine($"{ex.Message},{ex.SocketErrorCode}");
  88. // 如果错误代码为10048,则表示地址已被使用
  89. if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
  90. {
  91. isPortAvailable = false;
  92. }
  93. if (ex.SocketErrorCode==SocketError.ConnectionRefused)
  94. {
  95. isPortAvailable=true;
  96. }
  97. }
  98. catch (Exception ex)
  99. {
  100. Console.WriteLine(ex.Message);
  101. isPortAvailable = false;
  102. }
  103. return isPortAvailable;
  104. }
  105. }
  106. }