ProxyManager.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. using System.Linq;
  6. public class ProxyManager
  7. {
  8. private List<ProxyInfo> proxyPool = new List<ProxyInfo>();
  9. private object lockObj = new object();
  10. private DateTime lastResetTime = DateTime.UtcNow;
  11. private TimeSpan resetInterval = TimeSpan.FromHours(1); // 设置重置间隔为1小时
  12. public ProxyManager(IEnumerable<string> proxyAddresses)
  13. {
  14. foreach (var address in proxyAddresses)
  15. {
  16. proxyPool.Add(new ProxyInfo(new WebProxy(address)));
  17. }
  18. }
  19. public static WebProxy Parse(string proxy)
  20. {
  21. if (string.IsNullOrEmpty(proxy))
  22. {
  23. throw new ArgumentNullException(nameof(proxy));
  24. }
  25. try
  26. {
  27. string username = "";
  28. string password = "";
  29. string proxy_url = "";
  30. string scheme = "http://"; // 默认使用http
  31. // 检查是否指定了协议
  32. if (proxy.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
  33. proxy.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  34. {
  35. // 提取协议
  36. var schemeEnd = proxy.IndexOf("://");
  37. scheme = proxy[..(schemeEnd + 3)];
  38. proxy = proxy[(schemeEnd + 3)..];
  39. }
  40. // 检查是否包含认证信息
  41. if (proxy.Contains("@"))
  42. {
  43. var parts = proxy.Split('@');
  44. if (parts.Length == 2)
  45. {
  46. var credentials = parts[0].Split(':');
  47. if (credentials.Length == 2)
  48. {
  49. username = credentials[0];
  50. password = credentials[1];
  51. }
  52. proxy_url = parts[1];
  53. }
  54. }
  55. else
  56. {
  57. proxy_url = proxy;
  58. }
  59. // 构造完整的代理URL
  60. proxy_url = scheme + proxy_url;
  61. return new WebProxy
  62. {
  63. Address = new Uri(proxy_url),
  64. Credentials = !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)
  65. ? new NetworkCredential(username, password)
  66. : null
  67. };
  68. }
  69. catch (Exception ex)
  70. {
  71. throw new FormatException($"Failed to parse proxy string: {ex.Message}");
  72. }
  73. }
  74. public WebProxy GetNextProxy()
  75. {
  76. lock (lockObj)
  77. {
  78. if (DateTime.UtcNow - lastResetTime >= resetInterval) ResetCounters();
  79. var nextProxy = proxyPool.OrderBy(p => p.UsageCount).FirstOrDefault(p => p.IsAvailable);
  80. if (nextProxy != null)
  81. {
  82. nextProxy.UsageCount++;
  83. return nextProxy.Proxy;
  84. }
  85. return null; // 没有可用的代理时返回 null
  86. }
  87. }
  88. private void ResetCounters()
  89. {
  90. foreach (var proxyInfo in proxyPool)
  91. {
  92. proxyInfo.UsageCount = 0;
  93. }
  94. lastResetTime = DateTime.UtcNow;
  95. }
  96. public void ReportProxyResult(WebProxy proxy, bool isSuccess)
  97. {
  98. lock (lockObj)
  99. {
  100. var proxyInfo = proxyPool.Find(p => p.Proxy == proxy);
  101. if (proxyInfo != null)
  102. {
  103. if (isSuccess)
  104. {
  105. proxyInfo.Failures = 0;
  106. proxyInfo.IsAvailable = true;
  107. }
  108. else
  109. {
  110. proxyInfo.Failures++;
  111. proxyInfo.IsAvailable = false;
  112. proxyInfo.LastUnavailable = DateTime.UtcNow;
  113. if (proxyInfo.Failures >= 3)
  114. {
  115. proxyInfo.IsAvailable = false;
  116. SendAlert(proxyInfo);
  117. // 使用异步任务恢复代理可用状态
  118. Task.Run(async () =>
  119. {
  120. await Task.Delay(TimeSpan.FromMinutes(1));
  121. lock (lockObj)
  122. {
  123. // 只有在这段时间内没有再次标记为不可用时才重置代理状态
  124. if (!proxyInfo.IsAvailable)
  125. {
  126. proxyInfo.IsAvailable = true;
  127. }
  128. }
  129. });
  130. }
  131. }
  132. }
  133. }
  134. }
  135. private void SendAlert(ProxyInfo proxyInfo)
  136. {
  137. Console.WriteLine($"Alert: Proxy {proxyInfo.Proxy.Address} is repeatedly failing.");
  138. }
  139. }
  140. public class ProxyInfo
  141. {
  142. public WebProxy Proxy { get; }
  143. public bool IsAvailable { get; set; }
  144. public int UsageCount { get; set; }
  145. public int Failures { get; set; }
  146. public DateTime LastUnavailable { get; set; }
  147. public ProxyInfo(WebProxy proxy)
  148. {
  149. Proxy = proxy;
  150. IsAvailable = true;
  151. UsageCount = 0;
  152. Failures = 0;
  153. LastUnavailable = DateTime.MinValue;
  154. }
  155. }