AsyncClient.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using StressClient.common;
  8. using SuperSocket.ClientEngine;
  9. using SuperSocket.ClientEngine.Protocol;
  10. namespace StressClient
  11. {
  12. class AsyncClient
  13. {
  14. private SuperSocket.ClientEngine.AsyncTcpSession _client = null;
  15. private int _idx = -1;
  16. private string _clientId = "";
  17. //private string _svr_ip = "127.0.0.1";
  18. //private int _svr_port = 8081;
  19. private string _svr_ip = AppSetting.Instance().server_address;//"120.25.176.175";
  20. private int _svr_port = AppSetting.Instance().server_port;
  21. // 最后成功请求时间
  22. string _last_req_time = "";
  23. public AsyncClient(int idx, string clientId)
  24. {
  25. _idx = idx;
  26. _clientId = clientId;
  27. }
  28. public void Run()
  29. {
  30. try
  31. {
  32. string message = string.Format("{0} 客户端开始运行", _clientId);
  33. System.Console.WriteLine(message);
  34. // 创建连接
  35. InitConnection();
  36. System.Threading.Thread.Sleep(2000);
  37. while (true)
  38. {
  39. DateTime curTime = DateTime.Now;
  40. if (should_send_now(curTime))
  41. {
  42. // 发送数据
  43. SendRequest(curTime);
  44. }
  45. // 随机等待几秒
  46. Random rdm = new Random();
  47. int sleep_time = rdm.Next(5, 10);
  48. System.Threading.Thread.Sleep(sleep_time * 1000);
  49. }
  50. }
  51. catch (Exception e)
  52. {
  53. System.Console.WriteLine(e.Message);
  54. }
  55. }
  56. private void InitConnection()
  57. {
  58. try
  59. {
  60. if (_client != null)
  61. _client.Close();
  62. _client = new AsyncTcpSession();
  63. _client.Connect(new IPEndPoint(IPAddress.Parse(_svr_ip), _svr_port));
  64. // 连接断开事件
  65. _client.Closed += client_Closed;
  66. // 收到服务器数据事件
  67. _client.DataReceived += client_DataReceived;
  68. // 连接到服务器事件
  69. _client.Connected += client_Connected;
  70. // 发生错误的处理
  71. _client.Error += client_Error;
  72. }
  73. catch (Exception e)
  74. {
  75. System.Console.WriteLine(e.Message);
  76. }
  77. }
  78. public void SendRequest(DateTime curTime)
  79. {
  80. try
  81. {
  82. if (_client.IsConnected)
  83. {
  84. string message = string.Format("[{0}] ClientId {1} 客户端发送数据", DateTime.Now, _clientId);
  85. System.Console.WriteLine(message);
  86. // 拼装请求串
  87. //byte[] arr = Encoding.Default.GetBytes(string.Format("{0} {1}", "ADD", "DDDDDDDD\r\n"));
  88. string req_str = Helper.MakeReqStr1(_clientId, curTime);
  89. byte[] arr = Encoding.UTF8.GetBytes(req_str);
  90. _client.Send(arr, 0, arr.Length);
  91. // 发送成功,修改最新请求时间
  92. UpdateLastReqTime(curTime);
  93. }
  94. else
  95. {
  96. InitConnection();
  97. }
  98. }
  99. catch(Exception)
  100. {
  101. }
  102. }
  103. //判断当前时间是否在工作时间段内
  104. protected bool CheckTimeSpan(string timeStr)
  105. {
  106. string[] workTime = AppSetting.Instance().work_day_time_span;
  107. string strWorkingTimeStart1 = workTime[0];//工作时间上午11
  108. string strWorkingTimeEnd1 = workTime[1];
  109. string strWorkingTimeStart2 = workTime[2];//工作时间上午11
  110. string strWorkingTimeEnd2 = workTime[3];
  111. TimeSpan dspWorkingTimeStart1 = DateTime.Parse(strWorkingTimeStart1).TimeOfDay;
  112. TimeSpan dspWorkingTimeEnd1 = DateTime.Parse(strWorkingTimeEnd1).TimeOfDay;
  113. TimeSpan dspWorkingTimeStart2 = DateTime.Parse(strWorkingTimeStart2).TimeOfDay;
  114. TimeSpan dspWorkingTimeEnd2 = DateTime.Parse(strWorkingTimeEnd2).TimeOfDay;
  115. //string time1 = "2017-2-17 8:10:00";
  116. DateTime t1 = Convert.ToDateTime(timeStr);
  117. TimeSpan dspNow = t1.TimeOfDay;
  118. if ((dspNow > dspWorkingTimeStart1 && dspNow < dspWorkingTimeEnd1)|| (dspNow > dspWorkingTimeStart2 && dspNow < dspWorkingTimeEnd2))
  119. {
  120. return true;
  121. }
  122. return false;
  123. }
  124. // 是否到了发送时间
  125. private bool should_send_now(DateTime curTime)
  126. {
  127. //判断当前时间是否在工作时间段内
  128. if (!CheckTimeSpan(curTime.ToString("yyyy-MM-dd HH:mm:ss")))
  129. {
  130. return false;
  131. }
  132. // 从未发送过
  133. if (_last_req_time == "")
  134. return true;
  135. // 分钟填5的倍数,秒填00
  136. int minute = curTime.Minute - curTime.Minute % 5;
  137. Object[] param = new Object[] { curTime.Year, curTime.Month, curTime.Day, curTime.Hour, minute, 0 };
  138. string cur_dt = string.Format("{0:D4}{1:D2}{2:D2}{3:D2}{4:D2}{5:D2}", param);
  139. // 此时刻已经请求过
  140. if (_last_req_time == cur_dt)
  141. return false;
  142. return true;
  143. //int t1 = (curTime.Hour * 100 + curTime.Minute) * 100 + curTime.Second;
  144. //int t2 = (curTime.Hour * 100 + minute) * 100 + 0;
  145. //// 不要偏离整5分太远
  146. //if (t1 - t2 < 25)
  147. //{
  148. // return true;
  149. //}
  150. //return false;
  151. }
  152. // 修改最新请求时间
  153. private void UpdateLastReqTime(DateTime curTime)
  154. {
  155. // 分钟填5的倍数,秒填00
  156. int minute = curTime.Minute - curTime.Minute % 5;
  157. Object[] param = new Object[] { curTime.Year, curTime.Month, curTime.Day, curTime.Hour, minute, 0 };
  158. string cur_dt = string.Format("{0:D4}{1:D2}{2:D2}{3:D2}{4:D2}{5:D2}", param);
  159. _last_req_time = cur_dt;
  160. }
  161. private void client_Error(object sender, ErrorEventArgs e)
  162. {
  163. string message = string.Format("[{0}] ClientId {1} 客户端错误, {2}", DateTime.Now, _clientId, e.Exception.Message);
  164. System.Console.WriteLine(message);
  165. this.Error(message);
  166. }
  167. private void client_Connected(object sender, EventArgs e)
  168. {
  169. string message = string.Format("[{0}] ClientId {1} 客户端连接成功", DateTime.Now, _clientId);
  170. System.Console.WriteLine(message);
  171. this.Info(message);
  172. }
  173. private void client_DataReceived(object sender, DataEventArgs e)
  174. {
  175. string msg = Encoding.Default.GetString(e.Data, 0, e.Length).ToString().Replace("\r\n", "");
  176. string message = string.Format("[{0}][{1}] Recv {2}", DateTime.Now, _clientId, msg);
  177. Console.WriteLine(message);
  178. this.Info(message);
  179. }
  180. private void client_Closed(object sender, EventArgs e)
  181. {
  182. AsyncTcpSession client = sender as AsyncTcpSession;
  183. string message = string.Format("[{0}] ClientId {1} 客户端连接断开", DateTime.Now, _clientId);
  184. System.Console.WriteLine(message);
  185. this.Warn(message);
  186. }
  187. }
  188. }