123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- using HTEX.ScreenClient.Services;
- using System.Diagnostics;
- using System.Management;
- using System.Net;
- using System.Net.Sockets;
- using System.Runtime.InteropServices;
- using System.Text.RegularExpressions;
- using TEAMModelOS.SDK.DI.Device;
- namespace HTEX.ScreenClient
- {
- public class Program
- {
- public static void Main(string[] args)
- {
-
- var builder = WebApplication.CreateBuilder(args);
- builder.WebHost.UseKestrel(options =>
- {
- // options.ListenAnyIP(CheckOrNewPort(1883), options => {/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
- options.ListenAnyIP(CheckOrNewPort(5000), options => {/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
- });
- //写在端口配置之前,并且在用到的DI之前。否则会导致DI注入失败
-
- builder.Services.AddControllers();
- builder.Services.AddHttpClient();
- builder.Services.AddHttpContextAccessor();
- builder.Services.AddHostedService<SignalRScreenClientHub>();
- builder.Services.AddSingleton<CoreDevice>();
- var app = builder.Build();
- app.UseHttpsRedirection();
- app.UseAuthorization();
- app.MapControllers();
- app.Run();
- }
- /// <summary>
- /// 检测端口是否可用,如果不可用,则递归调用本方法,直到可用为止
- /// </summary>
- /// <param name="port"></param>
- /// <returns></returns>
- public static int CheckOrNewPort(int port)
- {
- if (IsPortAvailable(port))
- {
- return port;
- }
- else
- {
- return CheckOrNewPort(port + 1);
- }
- }
- /// <summary>
- /// 探测端口是否可用
- /// </summary>
- /// <param name="port"></param>
- /// <returns></returns>
- public static bool IsPortAvailable(int port)
- {
- bool isPortAvailable = false;
- IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); // 本地地址
- try
- {
- using (Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
- {
- // 尝试连接到指定的IP地址和端口
- IAsyncResult result = socket.BeginConnect(ipAddress, port, null, null);
- // 等待连接尝试完成(这里简单地使用Socket的ConnectTimeout,但更常见的做法是使用超时等待或异步回调)
- bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1), true);
- if (success)
- {
- // 如果连接成功,则端口被占用
- socket.EndConnect(result);
- isPortAvailable = false;
- // 可选:如果需要,可以在这里关闭连接
- //socket.Shutdown(SocketShutdown.Both);
- //socket.Close();
- }
- else
- {
- isPortAvailable = true;
- }
- }
- }
- catch (SocketException ex)
- {
- Console.WriteLine($"{ex.Message},{ex.SocketErrorCode}");
- // 如果错误代码为10048,则表示地址已被使用
- if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
- {
- isPortAvailable = false;
- }
- if (ex.SocketErrorCode==SocketError.ConnectionRefused)
- {
- isPortAvailable=true;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- isPortAvailable = false;
- }
- return isPortAvailable;
- }
- }
- }
|