CommonHelper.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. using FCS.Models;
  2. using FCS.Models.DTO;
  3. using HtmlAgilityPack;
  4. using Newtonsoft.Json;
  5. using Quartz;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Configuration;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Reflection;
  14. using System.Runtime.Remoting.Messaging;
  15. using System.Text;
  16. using System.Text.RegularExpressions;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Xml;
  20. namespace FCS.Common
  21. {
  22. /// <summary>
  23. /// 公用帮助类
  24. /// </summary>
  25. public static class CommonHelper
  26. {
  27. /// <summary>
  28. /// 将XML内容转换成目标对象实体集合
  29. /// </summary>
  30. /// <typeparam name="T">目标对象实体</typeparam>
  31. /// <param name="FileName">完整文件名(根目录下只需文件名称)</param>
  32. /// <param name="WrapperNodeName"></param>
  33. /// <returns></returns>
  34. public static List<T> ConvertXMLToObject<T>(string FileName, string WrapperNodeName)
  35. {
  36. XmlDocument doc = new XmlDocument();
  37. doc.Load(FileName);
  38. List<T> result = new List<T>();
  39. var TType = typeof(T);
  40. XmlNodeList nodeList = doc.ChildNodes;
  41. if (!string.IsNullOrEmpty(WrapperNodeName))
  42. {
  43. foreach (XmlNode node in doc.ChildNodes)
  44. {
  45. if (node.Name == WrapperNodeName)
  46. {
  47. nodeList = node.ChildNodes;
  48. break;
  49. }
  50. }
  51. }
  52. object oneT = null;
  53. foreach (XmlNode node in nodeList)
  54. {
  55. if (node.NodeType == XmlNodeType.Comment || node.NodeType == XmlNodeType.XmlDeclaration) continue;
  56. oneT = TType.Assembly.CreateInstance(TType.FullName);
  57. foreach (XmlNode item in node.ChildNodes)
  58. {
  59. if (item.NodeType == XmlNodeType.Comment) continue;
  60. var property = TType.GetProperty(item.Name);
  61. if (property != null)
  62. property.SetValue(oneT, Convert.ChangeType(item.InnerText, property.PropertyType), null);
  63. }
  64. result.Add((T)oneT);
  65. }
  66. return result;
  67. }
  68. /// <summary>
  69. /// 从作业数据地图中获取配置信息
  70. /// </summary>
  71. /// <param name="datamap">作业数据地图</param>
  72. /// <returns></returns>
  73. public static FCSConfig GetConfigFromDataMap(JobDataMap datamap)
  74. {
  75. FCSConfig config = new FCSConfig();
  76. var properties = typeof(FCSConfig).GetProperties();
  77. foreach (PropertyInfo info in properties)
  78. {
  79. if (info.PropertyType == typeof(string))
  80. info.SetValue(config, datamap.GetString(info.Name), null);
  81. else if (info.PropertyType == typeof(Int32))
  82. info.SetValue(config, datamap.GetInt(info.Name), null);
  83. }
  84. return config;
  85. }
  86. #region 日志信息
  87. public static string GetJobMainLogInfo(string QiHao)
  88. {
  89. return string.Format("通过主站地址抓取{0}期开奖数据成功", QiHao);
  90. }
  91. public static string GetJobLogError(string QiHao)
  92. {
  93. return string.Format("【{0}】抓取期开奖数据失败", QiHao);
  94. }
  95. #endregion 日志信息
  96. /// <summary>
  97. /// 将值转换为T类型数据
  98. /// </summary>
  99. /// <typeparam name="T">目标类型</typeparam>
  100. /// <param name="value">数据值</param>
  101. /// <returns></returns>
  102. public static T ChangeType<T>(object value)
  103. {
  104. return ChangeType<T>(value, default(T));
  105. }
  106. /// <summary>
  107. /// 将值转换为T类型数据,失败则返回T类型默认值
  108. /// </summary>
  109. /// <typeparam name="T">目标类型</typeparam>
  110. /// <param name="value">数据值</param>
  111. /// <param name="defaultValue">T类型默认值</param>
  112. /// <returns></returns>
  113. public static T ChangeType<T>(object value, T defaultValue)
  114. {
  115. if (value != null)
  116. {
  117. Type nullableType = typeof(T);
  118. if (!nullableType.IsInterface && (!nullableType.IsClass || (nullableType == typeof(string))))
  119. {
  120. if (nullableType.IsGenericType && (nullableType.GetGenericTypeDefinition() == typeof(Nullable<>)))
  121. {
  122. return (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(nullableType));
  123. }
  124. if (nullableType.IsEnum)
  125. {
  126. return (T)Enum.Parse(nullableType, value.ToString());
  127. }
  128. return (T)Convert.ChangeType(value, nullableType);
  129. }
  130. if (value is T)
  131. {
  132. return (T)value;
  133. }
  134. }
  135. return defaultValue;
  136. }
  137. /// <summary>
  138. /// 将值转换为type类型的值
  139. /// </summary>
  140. /// <param name="value">值</param>
  141. /// <param name="type">目标类型</param>
  142. /// <returns></returns>
  143. public static object ChangeType(object value, Type type)
  144. {
  145. if (value != null)
  146. {
  147. var nullableType = Nullable.GetUnderlyingType(type);
  148. if (nullableType != null)//可空
  149. {
  150. return Convert.ChangeType(value, nullableType);
  151. }
  152. if (Convert.IsDBNull(value))//特殊处理,由于数据库类型与项目中的类型定义不匹配
  153. return type.IsValueType ? Activator.CreateInstance(type) : null;
  154. return Convert.ChangeType(value, type);
  155. }
  156. return null;
  157. }
  158. #region 获取全局唯一GUID
  159. /// <summary>
  160. /// 获取全局唯一GUID
  161. /// </summary>
  162. /// <param name="needReplace">是否需要替换-</param>
  163. /// <param name="format">格式化</param>
  164. /// <example>N:38bddf48f43c48588e0d78761eaa1ce6</example>>
  165. /// <example>P:(778406c2-efff-4262-ab03-70a77d09c2b5)</example>>
  166. /// <example>B:{09f140d5-af72-44ba-a763-c861304b46f8}</example>>
  167. /// <example>D:57d99d89-caab-482a-a0e9-a0a803eed3ba</example>>
  168. /// <returns></returns>
  169. public static string GetGuid(bool needReplace = true, string format = "N")
  170. {
  171. Guid res = NewSequentialGuid();//Guid.NewGuid();
  172. return needReplace ? res.ToString(format) : res.ToString();
  173. }
  174. [System.Runtime.InteropServices.DllImport("rpcrt4.dll", SetLastError = true)]
  175. static extern int UuidCreateSequential(byte[] buffer);
  176. /// <summary>
  177. /// 创建有序GUID
  178. /// </summary>
  179. /// <returns></returns>
  180. private static Guid NewSequentialGuid()
  181. {
  182. byte[] raw = new byte[16];
  183. if (UuidCreateSequential(raw) != 0)
  184. throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
  185. byte[] fix = new byte[16];
  186. // reverse 0..3
  187. fix[0x0] = raw[0x3];
  188. fix[0x1] = raw[0x2];
  189. fix[0x2] = raw[0x1];
  190. fix[0x3] = raw[0x0];
  191. // reverse 4 & 5
  192. fix[0x4] = raw[0x5];
  193. fix[0x5] = raw[0x4];
  194. // reverse 6 & 7
  195. fix[0x6] = raw[0x7];
  196. fix[0x7] = raw[0x6];
  197. // all other are unchanged
  198. fix[0x8] = raw[0x8];
  199. fix[0x9] = raw[0x9];
  200. fix[0xA] = raw[0xA];
  201. fix[0xB] = raw[0xB];
  202. fix[0xC] = raw[0xC];
  203. fix[0xD] = raw[0xD];
  204. fix[0xE] = raw[0xE];
  205. fix[0xF] = raw[0xF];
  206. return new Guid(fix);
  207. }
  208. #endregion 获取全局唯一GUID
  209. #region HtmlAgilityPack
  210. public static int IpCount;
  211. public static List<string> IpList;
  212. public static string GetIp(string path = "", bool isGetIp = true)
  213. {
  214. if (isGetIp && IpList.Count > 0)
  215. {
  216. var ran = new Random().Next(0, IpList.Count);
  217. return IpList[ran];
  218. }
  219. if (path.IsEmpty())
  220. path = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IP.txt";
  221. StreamReader sr;
  222. try
  223. {
  224. sr = new StreamReader(path, System.Text.Encoding.GetEncoding("utf-8"));
  225. }
  226. catch (Exception)
  227. {
  228. Thread.Sleep(1000);
  229. sr = new StreamReader(path, System.Text.Encoding.GetEncoding("utf-8"));
  230. }
  231. string content = sr.ReadToEnd().ToString();
  232. sr.Close();
  233. var list = content.JsonToList<string>();
  234. content = "";
  235. if (isGetIp)
  236. IpList = list;
  237. var ram = new Random().Next(0, list.Count);
  238. IpCount = list.Count;
  239. return list[ram];
  240. }
  241. static object locker = new object();
  242. static bool isGetIp = false;
  243. public delegate string GetIPDataBYOne(List<string> _urlList, string _title = "", bool isFormData = false);
  244. public delegate string GetIPDataBYOne_FormData(List<string> _urlList, Dictionary<string, string> formData, string _title = "");
  245. /// <summary>
  246. /// 获取HTML
  247. /// </summary>
  248. /// <param name="model">参数实体</param>
  249. /// <returns></returns>
  250. public static HtmlDocument GetHtmlHtmlDocument(HtmlParameterDTO model)
  251. {
  252. var html = string.Empty;
  253. if (model.IsWebClient)
  254. html = GetHtmlByWebClient(model);
  255. else
  256. html = GetHtmlByIP(model);
  257. var doc = new HtmlDocument();
  258. doc.LoadHtml(html);
  259. return doc;
  260. }
  261. /// <summary>
  262. /// 获取HTML
  263. /// </summary>
  264. /// <param name="model">参数实体</param>
  265. /// <returns></returns>
  266. public static string GetHtmlString(HtmlParameterDTO model)
  267. {
  268. if (model.IsWebClient)
  269. return GetHtmlByWebClient(model);
  270. else
  271. return GetHtmlByIP(model);
  272. }
  273. /// <summary>
  274. /// 通过Ip获取页面的HTML
  275. /// </summary>
  276. /// <param name="model"></param>
  277. /// <returns></returns>
  278. private static string GetHtmlByIP(HtmlParameterDTO model)
  279. {
  280. var NotIpList = new List<string>();
  281. Stopwatch sw = new Stopwatch();
  282. sw.Start();
  283. var ip = model.IP.IsEmpty() ? GetIp() : model.IP;
  284. var httpItem = new HttpItem();
  285. lock (locker)
  286. {
  287. httpItem = Mapper<HttpItem>(model);
  288. httpItem.WebProxy = new WebProxy(ip);
  289. }
  290. var html = new HttpHelper().GetHtml(httpItem);
  291. //对文本的检查
  292. while ((model.IsCheckEmpty && html.Html.IsEmpty())
  293. || html.Html == ConfigurationManager.AppSettings["HttpException"].ToString()
  294. || (html.Html.Contains("403") && html.Html.ToLower().Contains("forbidden"))
  295. || ((html.Html.Contains("HTTP Status 404") || html.Html.Contains("404 Not Found")) && html.Html.ToLower().Contains("not found"))
  296. || html.Html.Contains("502 Bad Gateway")
  297. || html.Html.Contains("400 Bad Request")
  298. || (html.Html.Contains("301 Moved Permanently") && html.Html.ToLower().Contains("moved permanently"))
  299. || (html.Html.Contains("The requested URL could not be retrieved") && html.Html.ToLower().Contains("could not be retrieved"))
  300. || html.Html.Contains("缓存访问被拒绝")
  301. || html.Html.Contains("无效用户")
  302. || (!model.Title.IsEmpty() && !html.Html.Contains(model.Title)))
  303. {
  304. if (html.Html.ToLower().Contains("exception report"))
  305. {
  306. return ConfigurationManager.AppSettings["Termination"].ToString();
  307. }
  308. NotIpList.Add(ip);
  309. if (NotIpList.Distinct().ToList().Count == IpCount || NotIpList.Distinct().ToList().Count > model.NotIpNumber)
  310. {
  311. //EmailHelper.Send("1625453870@qq.com", "IP用完,未获取值的URL", "URL:" + model.Url + "||参数:" + model.FormData.TryToJson());
  312. //return ConfigurationManager.AppSettings["Termination"].ToString();
  313. LogBD(model.Url, "LogUrl", "UrlLog");
  314. return ConfigurationManager.AppSettings["Termination"].ToString();
  315. //IAsyncResult asyncResult;
  316. //lock (locker)
  317. //{
  318. // GetIPDataBYOne task = new GetIPDataBYOne(IPHelper.GetIPDataBYOne);
  319. // asyncResult = task.BeginInvoke(new List<string> { model.Url }, model.Title, false, null, null);
  320. // while (asyncResult != null && !asyncResult.AsyncWaitHandle.WaitOne(100, false))
  321. // {
  322. // }
  323. // ip = task.EndInvoke(asyncResult);
  324. // if (ip.IsEmpty())
  325. // return ConfigurationManager.AppSettings["Termination"].ToString();
  326. // else
  327. // return ip;
  328. //}
  329. }
  330. else
  331. {
  332. ip = ip = model.IP.IsEmpty() ? GetIp() : model.IP;
  333. while (NotIpList.Contains(ip) && model.IP.IsEmpty())
  334. ip = ip = model.IP.IsEmpty() ? GetIp() : model.IP;
  335. }
  336. httpItem.WebProxy = new WebProxy(ip);
  337. html = new HttpHelper().GetHtml(httpItem);
  338. }
  339. sw.Stop();
  340. Trace.WriteLine("url:" + model.Url + "||IP:" + ip + "||时间:" + sw.ElapsedMilliseconds + "毫秒");
  341. return html.Html;
  342. }
  343. /// <summary>
  344. /// 得到HtmlDocument
  345. /// </summary>
  346. /// <param name="url"></param>
  347. /// <param name="method"></param>
  348. /// <returns></returns>
  349. public static HtmlDocument GetHtml(string url, string title = "", bool isWebSoxket = false, string webProxy = "", string method = "get", int timeout = 90 * 1000, int notIpNUmber = 100)
  350. {
  351. return GetHtmlHtmlDocument(new HtmlParameterDTO
  352. {
  353. Url = url,
  354. Title = title,
  355. IP = webProxy,
  356. Method = method,
  357. Timeout = timeout,
  358. NotIpNumber = notIpNUmber
  359. });
  360. }
  361. /// <summary>
  362. /// 得到HtmlDocument
  363. /// From表单提交
  364. /// </summary>
  365. /// <param name="url"></param>
  366. /// <param name="method"></param>
  367. /// <returns></returns>
  368. public static HtmlDocument GetHtml(string url, Dictionary<string, string> formData, string title = "", string webProxy = "", int timeout = 90 * 1000, int notIpNUmber = 100)
  369. {
  370. // ContentType = "application/x-www-form-urlencoded",
  371. return GetHtmlHtmlDocument(new HtmlParameterDTO
  372. {
  373. Url = url,
  374. Title = title,
  375. IP = webProxy,
  376. Method = "POST",
  377. Timeout = timeout,
  378. NotIpNumber = notIpNUmber,
  379. ContentType = "application/x-www-form-urlencoded",
  380. FormData = formData
  381. });
  382. }
  383. #endregion
  384. #region WebClient请求
  385. private static string GetHtmlByWebClient(HtmlParameterDTO model)
  386. {
  387. using (var webClient = new WebClient())
  388. {
  389. webClient.Credentials = CredentialCache.DefaultCredentials;
  390. byte[] pageDate = webClient.DownloadData(model.Url);
  391. var content = Encoding.UTF8.GetString(pageDate);
  392. webClient.Dispose();
  393. return content;
  394. }
  395. }
  396. #endregion
  397. #region lg
  398. /// <summary>
  399. /// 得到HtmlDocument
  400. /// </summary>
  401. /// <param name="url"></param>
  402. /// <param name="method"></param>
  403. /// <returns></returns>
  404. public static string GetHtmlString(string url, string title = "", int timeout = 90 * 1000, bool isWebSoxket = false, string webProxy = "", string method = "get", int notIpNUmber = 100)
  405. {
  406. var NotIpList = new List<string>();
  407. var ip = webProxy.IsEmpty() ? GetIp() : webProxy;
  408. var html = new HttpHelper().GetHtml(new HttpItem
  409. {
  410. Url = url,
  411. Method = method,
  412. WebProxy = new WebProxy(ip),
  413. Timeout = timeout
  414. });
  415. int number = 0;
  416. if (!isWebSoxket)
  417. {
  418. while (html.Html.IsEmpty() || html.Html == ConfigurationManager.AppSettings["HttpException"].ToString() || (html.Html.IndexOf("403") != -1 && html.Html.ToLower().IndexOf("forbidden") != -1)
  419. || (html.Html.IndexOf("HTTP Status 404") != -1 && html.Html.ToLower().IndexOf("not found") != -1)
  420. || (!title.IsEmpty() && html.Html.IndexOf(title) == -1)
  421. || html.Html == ConfigurationManager.AppSettings["HttpException"].ToString()
  422. || (html.Html.Contains("403") && html.Html.ToLower().Contains("forbidden"))
  423. || ((html.Html.Contains("HTTP Status 404") || html.Html.Contains("404 Not Found")) && html.Html.ToLower().Contains("not found"))
  424. || html.Html.Contains("502 Bad Gateway")
  425. || html.Html.Contains("400 Bad Request")
  426. || (html.Html.Contains("301 Moved Permanently") && html.Html.ToLower().Contains("moved permanently"))
  427. || (html.Html.Contains("The requested URL could not be retrieved") && html.Html.ToLower().Contains("could not be retrieved"))
  428. || html.Html.Contains("缓存访问被拒绝")
  429. || (title.IsEmpty() && !html.Html.Contains(title)))
  430. {
  431. number++;
  432. if (number > 40)
  433. return "";
  434. if (html.Html.ToLower().Contains("exception report"))
  435. {
  436. ConfigurationManager.AppSettings["Termination"].ToString();
  437. break;
  438. }
  439. NotIpList.Add(ip);
  440. if (NotIpList.Distinct().ToList().Count == IpCount)
  441. {
  442. //IAsyncResult asyncResult;
  443. //lock (locker)
  444. //{
  445. // GetIPDataBYOne task = new GetIPDataBYOne(IPHelper.GetIPDataBYOne);
  446. // asyncResult = task.BeginInvoke(new List<string> { url }, title, false, null, null);
  447. // while (asyncResult != null && !asyncResult.AsyncWaitHandle.WaitOne(100, false))
  448. // {
  449. // }
  450. // ip = task.EndInvoke(asyncResult);
  451. // if (ip.IsEmpty())
  452. // {
  453. return ConfigurationManager.AppSettings["Termination"].ToString();
  454. // break;
  455. // }
  456. //}
  457. //}
  458. }
  459. else
  460. ip = webProxy.IsEmpty() ? GetIp() : webProxy;
  461. while (NotIpList.Contains(ip))
  462. ip = webProxy.IsEmpty() ? GetIp() : webProxy;
  463. html = new HttpHelper().GetHtml(new HttpItem
  464. {
  465. Url = url,
  466. Method = method,
  467. WebProxy = new WebProxy(ip)
  468. });
  469. }
  470. }
  471. return html.Html;
  472. }
  473. /// <summary>
  474. /// 得到HtmlDocument
  475. /// </summary>
  476. /// <param name="url"></param>
  477. /// <param name="method"></param>
  478. /// <returns></returns>
  479. public static HttpResult GetPostHtmlString(string url, HttpItem model, string title = "", int timeout = 90 * 1000, bool isWebSoxket = false, string webProxy = "", string method = "get", int notIpNUmber = 100)
  480. {
  481. model.Timeout = timeout;
  482. var html = new HttpHelper().GetHtml(model);
  483. if (!isWebSoxket)
  484. {
  485. var number = 0;
  486. while (html.Html.IsEmpty() || html.Html == ConfigurationManager.AppSettings["HttpException"].ToString() || (html.Html.IndexOf("403") != -1 && html.Html.ToLower().IndexOf("forbidden") != -1)
  487. || (html.Html.IndexOf("HTTP Status 404") != -1 && html.Html.ToLower().IndexOf("not found") != -1)
  488. || (!title.IsEmpty() && html.Html.IndexOf(title) == -1))
  489. {
  490. number++;
  491. if (number > 20)
  492. return html;
  493. model.WebProxy = new WebProxy(GetIp());
  494. html = new HttpHelper().GetHtml(model);
  495. }
  496. }
  497. return html;
  498. }
  499. public static string GetHtmlString_ceshi(string url = "http://fenxi.zgzcw.com/2321966/bjop", string title = "", bool isWebSoxket = false, string webProxy = "", string method = "get")
  500. {
  501. var html3 = new HttpHelper().GetHtml(new HttpItem
  502. {
  503. Url = url,
  504. Method = method,
  505. WebProxy = new WebProxy("113.124.93.1:601")
  506. });
  507. html3 = new HttpHelper().GetHtml(new HttpItem
  508. {
  509. Url = url,
  510. Method = method,
  511. WebProxy = new WebProxy("117.91.249.95:601")
  512. });
  513. F_Grouping g = new F_Grouping();
  514. List<string> list = new List<string>();
  515. list.Add("27.26.162.129");
  516. list.Add("117.91.249.95");
  517. list.Add("222.189.190.117");
  518. list.Add("222.189.191.254");
  519. list.Add("111.72.57.234");
  520. list.Add("113.124.93.1");
  521. list.Add("60.189.167.102");
  522. list.Add("180.118.141.126");
  523. list.Add("221.230.123.45");
  524. list.Add("221.230.123.101");
  525. list.Add("221.230.124.127");
  526. list.Add("125.125.45.149");
  527. list.Add("182.34.32.90");
  528. list.Add("113.121.46.19");
  529. list.Add("113.121.45.103");
  530. list.Add("113.121.23.219");
  531. list.Add("111.72.56.135");
  532. list.Add("111.72.63.12");
  533. list.Add("111.72.62.174");
  534. list.Add("111.72.58.28");
  535. list.Add("111.72.62.226");
  536. list.Add("106.226.227.245");
  537. list.Add("111.79.173.163");
  538. list.Add("106.7.78.39");
  539. list.Add("182.84.86.158");
  540. list.Add("182.100.238.11");
  541. list.Add("111.72.107.203");
  542. List<int> ss = new List<int>();
  543. for (int i = 0; i < 65535; i++)
  544. {
  545. ss.Add(i + 1);
  546. }
  547. int max1 = list.Count;
  548. int num1 = 0;
  549. list.ForEach(async p =>
  550. {
  551. await Task.Run(() =>
  552. {
  553. int max = 65535;
  554. int num = 0;
  555. //比赛
  556. ss.ForEach(async p1 =>
  557. {
  558. await Task.Run(() =>
  559. {
  560. var html = new HttpHelper().GetHtml(new HttpItem
  561. {
  562. Url = url,
  563. Method = method,
  564. WebProxy = new WebProxy(p + ":" + p1)
  565. });
  566. });
  567. lock (g)
  568. {
  569. num++;
  570. Monitor.Pulse(g); //完成,通知等待队列,告知已完,执行下一个。
  571. }
  572. });
  573. lock (g)
  574. {
  575. while (num < max)
  576. {
  577. Monitor.Wait(g);//等待
  578. }
  579. }
  580. });
  581. lock (g)
  582. {
  583. num1++;
  584. Monitor.Pulse(g); //完成,通知等待队列,告知已完,执行下一个。
  585. }
  586. });
  587. lock (g)
  588. {
  589. while (num1 < max1)
  590. {
  591. Monitor.Wait(g);//等待
  592. }
  593. }
  594. //if (!isWebSoxket)
  595. //{
  596. // var number = 0;
  597. // while (html.Html.IsEmpty() || (html.Html.IndexOf("403") != -1 && html.Html.ToLower().IndexOf("forbidden") != -1)
  598. // || (html.Html.IndexOf("HTTP Status 404") != -1 && html.Html.ToLower().IndexOf("not found") != -1)
  599. // || (!title.IsEmpty() && html.Html.IndexOf(title) == -1))
  600. // {
  601. // number++;
  602. // if (number > 100)
  603. // return null;
  604. // //if (number > IpCount)
  605. // html = new HttpHelper().GetHtml(new HttpItem
  606. // {
  607. // Url = url,
  608. // Method = method,
  609. // WebProxy = new WebProxy(CommonHelper.GetIp())
  610. // });
  611. // }
  612. //}
  613. return "";
  614. }
  615. #endregion
  616. #region 时间
  617. /// <summary>
  618. /// 将c# DateTime时间格式转换为Unix时间戳格式
  619. /// </summary>
  620. /// <param name="time">时间</param>
  621. /// <returns>long</returns>
  622. public static long ConvertDateTimeToInt(System.DateTime time)
  623. {
  624. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
  625. long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
  626. return t;
  627. }
  628. /// <summary>
  629. /// 时间戳转时间
  630. /// </summary>
  631. /// <param name="unixTimeStamp"></param>
  632. /// <returns></returns>
  633. public static DateTime ConvertIntToDateTime(string unixTimeStamp)
  634. {
  635. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  636. long lTime = long.Parse(unixTimeStamp + "0000");
  637. TimeSpan toNow = new TimeSpan(lTime);
  638. DateTime targetDt = dtStart.Add(toNow);
  639. return dtStart.Add(toNow);
  640. }
  641. #endregion
  642. /// <summary>
  643. /// 线程是否执行完成
  644. /// </summary>
  645. /// <returns></returns>
  646. public static bool ThreadsFinsh()
  647. {
  648. int maxWorkerThreads, workerThreads;
  649. int maxportThreads, portThreads;
  650. /*
  651. GetAvailableThreads():检索由 GetMaxThreads 返回的线程池线程的最大数目和当前活动数目之间的差值。
  652. 而GetMaxThreads 检索可以同时处于活动状态的线程池请求的数目。
  653. 通过最大数目减可用数目就可以得到当前活动线程的数目,如果为零,那就说明没有活动线程,说明所有线程运行完毕。
  654. */
  655. ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxportThreads);
  656. ThreadPool.GetAvailableThreads(out workerThreads, out portThreads);
  657. Thread.Sleep(3000);
  658. Trace.WriteLine("正在执行任务的线程数" + (maxWorkerThreads - workerThreads));
  659. if (maxWorkerThreads - workerThreads == 0)
  660. {
  661. Trace.WriteLine("加载完成!");
  662. return true;
  663. }
  664. return false;
  665. }
  666. /// <summary>
  667. /// 线程是否执行完成
  668. /// </summary>
  669. /// <returns></returns>
  670. public static bool ThreadsFinsh_new()
  671. {
  672. int maxWorkerThreads, workerThreads;
  673. int maxportThreads, portThreads;
  674. /*
  675. GetAvailableThreads():检索由 GetMaxThreads 返回的线程池线程的最大数目和当前活动数目之间的差值。
  676. 而GetMaxThreads 检索可以同时处于活动状态的线程池请求的数目。
  677. 通过最大数目减可用数目就可以得到当前活动线程的数目,如果为零,那就说明没有活动线程,说明所有线程运行完毕。
  678. */
  679. ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxportThreads);
  680. ThreadPool.GetAvailableThreads(out workerThreads, out portThreads);
  681. Thread.Sleep(3000);
  682. Trace.WriteLine("正在执行任务的线程数" + (maxWorkerThreads - workerThreads - 3));
  683. if (maxWorkerThreads - workerThreads - 3 == 0)
  684. {
  685. Trace.WriteLine("加载完成!");
  686. return true;
  687. }
  688. return false;
  689. }
  690. /// <summary>
  691. /// 文件写入
  692. /// </summary>
  693. public static void Write(string path, string data)
  694. {
  695. using (var fs = new FileStream(path, FileMode.Append))
  696. {
  697. using (var sw = new StreamWriter(fs))
  698. {
  699. sw.WriteLine(data);
  700. sw.Flush();
  701. }
  702. }
  703. }
  704. public static void Write_IP(string path, string data)
  705. {
  706. using (var fs = new FileStream(path, FileMode.Create))
  707. {
  708. using (var sw = new StreamWriter(fs, Encoding.UTF8))
  709. {
  710. sw.Write(data);
  711. sw.Flush();
  712. }
  713. }
  714. }
  715. public static void LogBD(string content, string pathName = "", string directoryName = "Log")
  716. {
  717. if (pathName.IsEmpty())
  718. pathName = content;
  719. var path = AppDomain.CurrentDomain.BaseDirectory + "/" + directoryName;
  720. CreateDirectory(path);
  721. path += $"/{DateTime.Now.ToString("yyyyMMdd")}";
  722. CreateDirectory(path);
  723. Write(path + $"/{pathName}.txt", content + "||" + DateTime.Now.ToString());
  724. }
  725. /// <summary>
  726. /// 创建文件夹
  727. /// </summary>
  728. /// <param name="paht"></param>
  729. private static void CreateDirectory(string path)
  730. {
  731. if (!Directory.Exists(path))
  732. Directory.CreateDirectory(path);
  733. }
  734. public static T Mapper<T>(object data)
  735. {
  736. return AutoMapper.Mapper.DynamicMap<T>(data);
  737. }
  738. //获取外网IP
  739. public static string GetExternalIP()
  740. {
  741. using (var webClient = new WebClient())
  742. {
  743. try
  744. {
  745. webClient.Credentials = CredentialCache.DefaultCredentials;
  746. byte[] pageDate = webClient.DownloadData("http://pv.sohu.com/cityjson?ie=utf-8");
  747. String ip = Encoding.UTF8.GetString(pageDate); webClient.Dispose();
  748. Match rebool = Regex.Match(ip, @"\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"); return rebool.Value;
  749. }
  750. catch (Exception e)
  751. {
  752. return "";
  753. }
  754. }
  755. }
  756. }
  757. class AsyncSemaphore
  758. {
  759. private readonly static Task s_completed = Task.FromResult(true);
  760. private readonly Queue<TaskCompletionSource<bool>> m_waiters = new Queue<TaskCompletionSource<bool>>();
  761. private int m_currentCount;
  762. public AsyncSemaphore(int initialCount)
  763. {
  764. if (initialCount < 0) throw new ArgumentOutOfRangeException("initialCount");
  765. m_currentCount = initialCount;
  766. }
  767. public Task WaitAsync()
  768. {
  769. lock (m_waiters)
  770. {
  771. if (m_currentCount > 0)
  772. {
  773. --m_currentCount;
  774. return s_completed;
  775. }
  776. else
  777. {
  778. var waiter = new TaskCompletionSource<bool>();
  779. m_waiters.Enqueue(waiter);
  780. return waiter.Task;
  781. }
  782. }
  783. }
  784. public void Release()
  785. {
  786. TaskCompletionSource<bool> toRelease = null;
  787. lock (m_waiters)
  788. {
  789. if (m_waiters.Count > 0)
  790. toRelease = m_waiters.Dequeue();
  791. else
  792. ++m_currentCount;
  793. }
  794. if (toRelease != null)
  795. toRelease.SetResult(true);
  796. }
  797. }
  798. public class AsyncLock
  799. {
  800. private readonly AsyncSemaphore m_semaphore;
  801. private readonly Task<Releaser> m_releaser;
  802. public AsyncLock()
  803. {
  804. m_semaphore = new AsyncSemaphore(1);
  805. m_releaser = Task.FromResult(new Releaser(this));
  806. }
  807. public Task<Releaser> LockAsync()
  808. {
  809. var wait = m_semaphore.WaitAsync();
  810. return wait.IsCompleted ?
  811. m_releaser :
  812. wait.ContinueWith((_, state) => new Releaser((AsyncLock)state),
  813. this, CancellationToken.None,
  814. TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
  815. }
  816. public struct Releaser : IDisposable
  817. {
  818. private readonly AsyncLock m_toRelease;
  819. internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; }
  820. public void Dispose()
  821. {
  822. if (m_toRelease != null)
  823. m_toRelease.m_semaphore.Release();
  824. }
  825. }
  826. }
  827. }