DnscryptProxyHostedService.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using FastGithub.Configuration;
  2. using Microsoft.Extensions.Hosting;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace FastGithub.DomainResolve
  8. {
  9. /// <summary>
  10. /// DnscryptProxy后台服务
  11. /// </summary>
  12. sealed class DnscryptProxyHostedService : IHostedService
  13. {
  14. private readonly FastGithubConfig fastGithubConfig;
  15. private readonly ILogger<DnscryptProxyHostedService> logger;
  16. private DnscryptProxy? dnscryptProxy;
  17. /// <summary>
  18. /// DnscryptProxy后台服务
  19. /// </summary>
  20. /// <param name="fastGithubConfig"></param>
  21. /// <param name="logger"></param>
  22. public DnscryptProxyHostedService(
  23. FastGithubConfig fastGithubConfig,
  24. ILogger<DnscryptProxyHostedService> logger)
  25. {
  26. this.fastGithubConfig = fastGithubConfig;
  27. this.logger = logger;
  28. }
  29. /// <summary>
  30. /// 启动dnscrypt-proxy
  31. /// </summary>
  32. /// <param name="cancellationToken"></param>
  33. /// <returns></returns>
  34. public async Task StartAsync(CancellationToken cancellationToken)
  35. {
  36. var pureDns = this.fastGithubConfig.PureDns;
  37. if (LocalMachine.ContainsIPAddress(pureDns.Address) == true)
  38. {
  39. this.dnscryptProxy = new DnscryptProxy(pureDns);
  40. try
  41. {
  42. await this.dnscryptProxy.StartAsync(cancellationToken);
  43. this.logger.LogInformation($"{this.dnscryptProxy}启动成功");
  44. }
  45. catch (Exception ex)
  46. {
  47. this.logger.LogWarning($"{this.dnscryptProxy}启动失败:{ex.Message}");
  48. }
  49. }
  50. }
  51. /// <summary>
  52. /// 停止dnscrypt-proxy
  53. /// </summary>
  54. /// <param name="cancellationToken"></param>
  55. /// <returns></returns>
  56. public Task StopAsync(CancellationToken cancellationToken)
  57. {
  58. if (this.dnscryptProxy != null)
  59. {
  60. try
  61. {
  62. this.dnscryptProxy.Stop();
  63. this.logger.LogInformation($"{this.dnscryptProxy}已停止");
  64. }
  65. catch (Exception ex)
  66. {
  67. this.logger.LogWarning($"{this.dnscryptProxy}停止失败:{ex.Message}");
  68. }
  69. }
  70. return Task.CompletedTask;
  71. }
  72. }
  73. }