TpcClient.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using SuperSocket.ClientEngine;
  2. using System.Net;
  3. using System.Text;
  4. using Vbdsm.Gen;
  5. using Vbdsm.Settings;
  6. namespace Vbdsm.SocketClients
  7. {
  8. public class TpcClient
  9. {
  10. private Dictionary<string, AsyncTcpSession> Clients { get; }
  11. private int MaxErrorCount { get; }
  12. private int MinuteInterval => 5;
  13. private long LastRequestTime { get; set; }
  14. private int ErrorCount { get; set; }
  15. private string? ClientId { get; }
  16. private string TerminalIds { get; }
  17. public TpcClient(string? clientId, string terminalIds)
  18. {
  19. Clients = GenClients();
  20. MaxErrorCount = AppSetting.Instance.MaxErrorCount;
  21. ClientId = clientId;
  22. TerminalIds = terminalIds;
  23. //LastRequestTime = CalcCurrentTime();
  24. }
  25. private Dictionary<string, AsyncTcpSession> GenClients()
  26. {
  27. var clients = new Dictionary<string, AsyncTcpSession>();
  28. foreach (var server in AppSetting.Instance.Servers)
  29. {
  30. var key = $"{server.Ip}:{server.Port}";
  31. if (!clients.ContainsKey(key))
  32. {
  33. var client = InitClient(key);
  34. clients.Add(key, client);
  35. }
  36. }
  37. return clients;
  38. }
  39. private AsyncTcpSession InitClient(string key, AsyncTcpSession? client = null)
  40. {
  41. if (client != null)
  42. client.Close();
  43. client = new AsyncTcpSession();
  44. try
  45. {
  46. var arr = key.Split(':');
  47. var ip = arr[0];
  48. var port = arr[1];
  49. if (arr.Length < 2)
  50. {
  51. return client;
  52. }
  53. // 连接断开事件
  54. client.Closed += (sender, _) =>
  55. {
  56. client = sender as AsyncTcpSession;
  57. string message = $"[{DateTime.Now}] :客户端【{ClientId}】【{ip}:{port}】连接断开。";
  58. Console.WriteLine(message);
  59. };
  60. // 收到服务器数据事件
  61. client.DataReceived += (_, e) =>
  62. {
  63. string msg = Encoding.Default.GetString(e.Data, 0, e.Length).ToString().Replace("\r\n", "");
  64. string message = $"[{DateTime.Now}] 客户端【{ClientId}】【{ip}:{port}】接受消息 => {msg}。";
  65. Console.WriteLine(message);
  66. };
  67. // 连接到服务器事件
  68. client.Connected += (_, _) =>
  69. {
  70. string message = $"[{DateTime.Now}] 客户端【{ClientId}】【{ip}:{port}】连接成功。";
  71. Console.WriteLine(message);
  72. };
  73. // 发生错误的处理
  74. client.Error += (_, e) =>
  75. {
  76. string message = $"[{DateTime.Now}] 客户端【{ClientId}】【{ip}:{port}】错误 => {e.Exception.Message}";
  77. Console.WriteLine(message);
  78. };
  79. client.Connect(new IPEndPoint(IPAddress.Parse(ip), Convert.ToInt16(port)));
  80. }
  81. catch (Exception e)
  82. {
  83. Console.WriteLine(e.Message);
  84. }
  85. return client;
  86. }
  87. public void Run()
  88. {
  89. try
  90. {
  91. Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}@{TerminalIds}】开始运行");
  92. // 创建连接
  93. Thread.Sleep(2000);
  94. while (true)
  95. {
  96. Console.Write(".");
  97. Send();
  98. Thread.Sleep(2 * 1000);
  99. }
  100. }
  101. catch (Exception e)
  102. {
  103. Console.WriteLine(e.Message);
  104. }
  105. }
  106. public void ReSend()
  107. {
  108. Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】 手动触发 ==>");
  109. Send(false);
  110. }
  111. private void Send(bool needCheck = true)
  112. {
  113. if (ErrorCount >= MaxErrorCount || needCheck && !CheckSend())
  114. {
  115. return;
  116. }
  117. try
  118. {
  119. LastRequestTime = CalcCurrentTime();
  120. string str = new GenData(TerminalIds, ClientId).GenTerminals(LastRequestTime);
  121. if (string.IsNullOrEmpty(str))
  122. {
  123. Console.WriteLine($"\r\n[{DateTime.Now}] 客户端【{ClientId}】[{LastRequestTime}] 已发送过数据! ");
  124. return;
  125. }
  126. Console.WriteLine($"\r\n[{DateTime.Now}] 客户端【{ClientId}】发送数据[{LastRequestTime}] ==> {str}");
  127. byte[] bytes = Encoding.UTF8.GetBytes(str);
  128. foreach (var kv in Clients)
  129. {
  130. ErrorCount = 0;
  131. Send(kv, bytes);
  132. }
  133. }
  134. catch (Exception e)
  135. {
  136. ErrorCount++;
  137. Console.WriteLine(e);
  138. }
  139. }
  140. private void Send(KeyValuePair<string, AsyncTcpSession> keyValue, byte[] bytes)
  141. {
  142. var client = keyValue.Value;
  143. if (client.IsConnected)
  144. {
  145. Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】【{keyValue.Key}】发送数据");
  146. client.Send(bytes, 0, bytes.Length);
  147. }
  148. else
  149. {
  150. client = InitClient(keyValue.Key, client);
  151. Clients.Remove(keyValue.Key);
  152. Clients.Add(keyValue.Key, client);
  153. ErrorCount++;
  154. Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】【{keyValue.Key}】连接失败 ==> {ErrorCount}/{MaxErrorCount}");
  155. Thread.Sleep(2 * 1000);
  156. if (ErrorCount <= MaxErrorCount)
  157. {
  158. Send(keyValue, bytes);
  159. }
  160. }
  161. }
  162. private bool CheckSend()
  163. {
  164. var time = CalcCurrentTime() - LastRequestTime;
  165. return time > 0;
  166. }
  167. private long CalcCurrentTime()
  168. {
  169. // DateTime timeUtc = DateTime.UtcNow;
  170. // TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
  171. // DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
  172. // Console.WriteLine(cstTime.ToString("yyyyMMddHHmmss"));
  173. //long time = Convert.ToInt64($"{DateTime.Now:yyyyMMddHH}{(DateTime.Now.Minute - DateTime.Now.Minute % minuteInterval):D2}00");
  174. long time = Convert.ToInt64($"{DateTime.Now:yyyyMMddHHmm00}");
  175. time -= (time - (time / 10000) * 10000) % (MinuteInterval * 100);
  176. return time;
  177. }
  178. }
  179. }