TpcClient.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 => 15;
  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. Console.WriteLine($"\r\n[{DateTime.Now}] 客户端【{ClientId}】发送数据[{LastRequestTime}] ==>");
  121. string str = new GenData(TerminalIds, ClientId).GenTerminals(LastRequestTime + "");
  122. byte[] bytes = Encoding.UTF8.GetBytes(str);
  123. foreach (var kv in Clients)
  124. {
  125. ErrorCount = 0;
  126. Send(kv, bytes);
  127. }
  128. }
  129. catch (Exception e)
  130. {
  131. ErrorCount++;
  132. Console.WriteLine(e);
  133. }
  134. }
  135. private void Send(KeyValuePair<string, AsyncTcpSession> keyValue, byte[] bytes)
  136. {
  137. var client = keyValue.Value;
  138. if (client.IsConnected)
  139. {
  140. Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】【{keyValue.Key}】发送数据");
  141. client.Send(bytes, 0, bytes.Length);
  142. }
  143. else
  144. {
  145. client = InitClient(keyValue.Key, client);
  146. Clients.Remove(keyValue.Key);
  147. Clients.Add(keyValue.Key, client);
  148. ErrorCount++;
  149. Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】【{keyValue.Key}】连接失败 ==> {ErrorCount}/{MaxErrorCount}");
  150. Thread.Sleep(2 * 1000);
  151. if (ErrorCount <= MaxErrorCount)
  152. {
  153. Send(keyValue, bytes);
  154. }
  155. }
  156. }
  157. private bool CheckSend()
  158. {
  159. var time = CalcCurrentTime() - LastRequestTime;
  160. return time > 0;
  161. }
  162. private long CalcCurrentTime()
  163. {
  164. //long time = Convert.ToInt64($"{DateTime.Now:yyyyMMddHH}{(DateTime.Now.Minute - DateTime.Now.Minute % minuteInterval):D2}00");
  165. long time = Convert.ToInt64($"{DateTime.Now:yyyyMMddHHmm00}");
  166. time -= (time - (time / 10000) * 10000) % (MinuteInterval * 100);
  167. return time;
  168. }
  169. }
  170. }