ReverseProxyHostedService.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using Microsoft.Extensions.Hosting;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace FastGithub.ReverseProxy
  8. {
  9. /// <summary>
  10. /// 反向代理端口检测后台服务
  11. /// </summary>
  12. sealed class ReverseProxyHostedService : IHostedService
  13. {
  14. private readonly ILogger<ReverseProxyHostedService> logger;
  15. /// <summary>
  16. /// 反向代理端口检测后台服务
  17. /// </summary>
  18. /// <param name="logger"></param>
  19. public ReverseProxyHostedService(ILogger<ReverseProxyHostedService> logger)
  20. {
  21. this.logger = logger;
  22. }
  23. public Task StartAsync(CancellationToken cancellationToken)
  24. {
  25. if (OperatingSystem.IsWindows())
  26. {
  27. const int HTTPSPORT = 443;
  28. if (TcpTable.TryGetOwnerProcessId(HTTPSPORT, out var pid))
  29. {
  30. try
  31. {
  32. Process.GetProcessById(pid).Kill();
  33. }
  34. catch (ArgumentException)
  35. {
  36. }
  37. catch (Exception)
  38. {
  39. var processName = Process.GetProcessById(pid).ProcessName;
  40. this.logger.LogError($"由于进程{processName}({pid})占用了{HTTPSPORT}端口,{nameof(FastGithub)}的反向代理无法工作");
  41. }
  42. }
  43. }
  44. return Task.CompletedTask;
  45. }
  46. public Task StopAsync(CancellationToken cancellationToken)
  47. {
  48. return Task.CompletedTask;
  49. }
  50. }
  51. }