TcpInterceptHostedService.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Microsoft.Extensions.Hosting;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Linq;
  7. using System.Runtime.Versioning;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace FastGithub.PacketIntercept
  11. {
  12. /// <summary>
  13. /// tcp拦截后台服务
  14. /// </summary>
  15. [SupportedOSPlatform("windows")]
  16. sealed class TcpInterceptHostedService : BackgroundService
  17. {
  18. private readonly IEnumerable<ITcpInterceptor> tcpInterceptors;
  19. private readonly ILogger<TcpInterceptHostedService> logger;
  20. private readonly IHost host;
  21. /// <summary>
  22. /// tcp拦截后台服务
  23. /// </summary>
  24. /// <param name="tcpInterceptors"></param>
  25. /// <param name="logger"></param>
  26. /// <param name="host"></param>
  27. public TcpInterceptHostedService(
  28. IEnumerable<ITcpInterceptor> tcpInterceptors,
  29. ILogger<TcpInterceptHostedService> logger,
  30. IHost host)
  31. {
  32. this.tcpInterceptors = tcpInterceptors;
  33. this.logger = logger;
  34. this.host = host;
  35. }
  36. /// <summary>
  37. /// https后台
  38. /// </summary>
  39. /// <param name="stoppingToken"></param>
  40. /// <returns></returns>
  41. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  42. {
  43. try
  44. {
  45. var tasks = this.tcpInterceptors.Select(item => item.InterceptAsync(stoppingToken));
  46. await Task.WhenAll(tasks);
  47. }
  48. catch (OperationCanceledException)
  49. {
  50. }
  51. catch (Win32Exception ex) when (ex.NativeErrorCode == 995)
  52. {
  53. }
  54. catch (Exception ex)
  55. {
  56. this.logger.LogError(ex, "tcp拦截器异常");
  57. await this.host.StopAsync(stoppingToken);
  58. }
  59. }
  60. }
  61. }