frmClient.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Threading;
  10. using System.Diagnostics;
  11. using HPSocketCS;
  12. namespace TcpClient_PFM
  13. {
  14. public enum AppState
  15. {
  16. Starting, Started, Stoping, Stoped, Error
  17. }
  18. public partial class frmClient : Form
  19. {
  20. private AppState appState = AppState.Stoped;
  21. private delegate void ShowMsg(string msg);
  22. private ShowMsg AddMsgDelegate;
  23. Stopwatch StopWatch = new Stopwatch();
  24. int TestTimes = 0;
  25. int TestInterv = 0;
  26. int ThreadCount = 0;
  27. int ThreadInterv = 0;
  28. int DataLength = 0;
  29. long Timeconsuming = 0;
  30. Int64 TotalReceived = 0;
  31. Int64 TotalSent = 0;
  32. Int64 ExpectReceived = 0;
  33. Thread testThread = null;
  34. List<TcpClient> clientList = new List<TcpClient>();
  35. public frmClient()
  36. {
  37. InitializeComponent();
  38. }
  39. private void frmClient_Load(object sender, EventArgs e)
  40. {
  41. // 初始化测试值
  42. this.cbxTestTime.SelectedIndex = 5;
  43. this.cbxTestInterv.SelectedIndex = 1;
  44. this.cbxThreadInterv.SelectedIndex = 0;
  45. this.cbxThreadCount.SelectedIndex = 5;
  46. this.cbxDataLength.SelectedIndex = 5;
  47. try
  48. {
  49. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  50. AddMsgDelegate = new ShowMsg(AddMsg);
  51. SetAppState(AppState.Stoped);
  52. AddMsg("提示:32位系统和程序,调整参数时,组合包的【大小】不要超过系统支持的内存。");
  53. }
  54. catch (Exception ex)
  55. {
  56. SetAppState(AppState.Error);
  57. AddMsg(ex.Message);
  58. }
  59. }
  60. private bool CheckParams()
  61. {
  62. bool ret = false;
  63. if (TestTimes <= 0)
  64. {
  65. this.cbxTestTime.Focus();
  66. }
  67. else if (TestInterv < 0)
  68. {
  69. this.cbxTestInterv.Focus();
  70. }
  71. else if (ThreadCount <= 0)
  72. {
  73. this.cbxThreadCount.Focus();
  74. }
  75. else if (ThreadInterv < 0)
  76. {
  77. this.cbxThreadInterv.Focus();
  78. }
  79. else if (DataLength <= 0)
  80. {
  81. this.cbxDataLength.Focus();
  82. }
  83. else
  84. {
  85. ret = true;
  86. }
  87. return ret;
  88. }
  89. private void btnStart_Click(object sender, EventArgs e)
  90. {
  91. try
  92. {
  93. string address = this.txtIpAddress.Text.Trim();
  94. ushort port = ushort.Parse(this.txtPort.Text.Trim());
  95. TestTimes = int.Parse(this.cbxTestTime.Text.Trim());
  96. TestInterv = int.Parse(this.cbxTestInterv.Text.Trim());
  97. ThreadCount = int.Parse(this.cbxThreadCount.Text.Trim());
  98. ThreadInterv = int.Parse(this.cbxThreadInterv.Text.Trim());
  99. DataLength = int.Parse(this.cbxDataLength.Text.Trim());
  100. if (CheckParams() == false)
  101. {
  102. throw new Exception("params error!");
  103. }
  104. SetAppState(AppState.Starting);
  105. Timeconsuming = 0;
  106. TotalReceived = 0;
  107. TotalSent = 0;
  108. ExpectReceived = (Int64)TestTimes * (Int64)ThreadCount * (Int64)DataLength;
  109. clientList.Clear();
  110. // 创建指定线程个数的客户端
  111. for (int i = 0; i < ThreadCount; i++)
  112. {
  113. TcpClient client = new TcpClient();
  114. // 设置client事件
  115. client.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
  116. client.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
  117. client.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
  118. client.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
  119. client.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);
  120. if (client.Connect(address, port) == true)
  121. {
  122. clientList.Add(client);
  123. }
  124. else
  125. {
  126. foreach (var c in clientList)
  127. {
  128. c.Stop();
  129. }
  130. clientList.Clear();
  131. throw new Exception(string.Format(" > {2}, Connection to server fail ->({0},{1})", client.ErrorCode, client.ErrorMessage, i));
  132. }
  133. }
  134. AddMsg(string.Format("$ Client start ok -> ({0}:{1})", address, port));
  135. // 延迟3秒
  136. int sendDelay = 3;
  137. AddMsg(string.Format(" *** willing to send data after {0} seconds ...", sendDelay));
  138. // Delay2(sendDelay * 1000);
  139. SetAppState(AppState.Started);
  140. testThread = new Thread(delegate()
  141. {
  142. Thread.Sleep(sendDelay * 1000);
  143. AddMsg(string.Format(" *** begin... ***", sendDelay));
  144. // 发送的数据包
  145. byte[] sendBytes = new byte[DataLength];
  146. StopWatch.Restart();
  147. bool isTerminated = false;
  148. for (int i = 0; i < TestTimes; i++)
  149. {
  150. for (int j = 0; j < ThreadCount; j++)
  151. {
  152. TcpClient client = clientList[j];
  153. if (client.Send(sendBytes, sendBytes.Length) == false)
  154. {
  155. AddMsg(string.Format("$ Client send fail [sock: {0}, seq: {1}] -> {3} ({2})",
  156. i + 1,
  157. j + 1,
  158. client.SYSGetLastError(),
  159. client.GetSocketErrorDesc(SocketError.DataSend)));
  160. isTerminated = true;
  161. break;
  162. }
  163. if (ThreadInterv > 0 && j + 1 < ThreadCount)
  164. {
  165. Thread.Sleep(ThreadInterv);
  166. //Delay2(ThreadInterv);
  167. }
  168. }
  169. if (isTerminated == true)
  170. {
  171. break;
  172. }
  173. if (TestInterv > 0 && i + 1 < TestTimes)
  174. {
  175. Thread.Sleep(TestInterv);
  176. //Delay2(TestInterv);
  177. }
  178. }
  179. });
  180. testThread.Start();
  181. }
  182. catch (Exception ex)
  183. {
  184. SetAppState(AppState.Stoped);
  185. AddMsg(string.Format("$ Start fail msg:{0}", ex.Message));
  186. }
  187. }
  188. private void btnStop_Click(object sender, EventArgs e)
  189. {
  190. SetAppState(AppState.Stoping);
  191. for (int i = 0; i < clientList.Count; i++)
  192. {
  193. if (clientList[i].Stop() == true)
  194. {
  195. AddMsg(string.Format("$ Client stopping ... --> ({0})", i + 1));
  196. }
  197. }
  198. if (testThread.ThreadState == System.Threading.ThreadState.Running)
  199. {
  200. testThread.Abort();
  201. }
  202. Delay2(100);
  203. AddMsg(string.Format("*** Summary: expect - {0}, send - {1}, recv - {2}",
  204. ExpectReceived, TotalSent, TotalReceived));
  205. if (ExpectReceived == TotalSent && TotalSent == TotalReceived)
  206. {
  207. AddMsg(string.Format(" *** Success: time consuming - {0} millisecond !", Timeconsuming));
  208. }
  209. else
  210. {
  211. AddMsg("*** Fail: manual terminated ? (or data lost)");
  212. }
  213. SetAppState(AppState.Stoped);
  214. }
  215. HandleResult OnPrepareConnect(TcpClient sender, uint socket)
  216. {
  217. return HandleResult.Ok;
  218. }
  219. HandleResult OnConnect(TcpClient sender)
  220. {
  221. // 已连接 到达一次
  222. AddMsg(string.Format(" > [{0}, OnConnect]", sender.ConnectionId));
  223. return HandleResult.Ok;
  224. }
  225. HandleResult OnSend(TcpClient sender, byte[] bytes)
  226. {
  227. // 客户端发数据了
  228. Interlocked.Add(ref TotalSent, bytes.Length);
  229. return HandleResult.Ok;
  230. }
  231. HandleResult OnReceive(TcpClient sender, byte[] bytes)
  232. {
  233. // 数据到达了
  234. Interlocked.Add(ref TotalReceived, bytes.Length);
  235. if (TotalReceived == ExpectReceived)
  236. {
  237. StopWatch.Stop();
  238. Timeconsuming = StopWatch.ElapsedMilliseconds;
  239. AddMsg(string.Format("Total time consuming: {0}", Timeconsuming));
  240. }
  241. return HandleResult.Ok;
  242. }
  243. HandleResult OnClose(TcpClient sender, SocketOperation enOperation, int errorCode)
  244. {
  245. // 连接关闭了
  246. return HandleResult.Ok;
  247. }
  248. /// <summary>
  249. /// 设置程序状态
  250. /// </summary>
  251. /// <param name="state"></param>
  252. void SetAppState(AppState state)
  253. {
  254. appState = state;
  255. this.btnStart.Enabled = (appState == AppState.Stoped);
  256. this.btnStop.Enabled = (appState == AppState.Started);
  257. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  258. this.txtPort.Enabled = (appState == AppState.Stoped);
  259. this.cbxTestTime.Enabled = (appState == AppState.Stoped);
  260. this.cbxTestInterv.Enabled = (appState == AppState.Stoped);
  261. this.cbxThreadInterv.Enabled = (appState == AppState.Stoped);
  262. this.cbxThreadCount.Enabled = (appState == AppState.Stoped);
  263. this.cbxDataLength.Enabled = (appState == AppState.Stoped);
  264. }
  265. /// <summary>
  266. /// 往listbox加一条项目
  267. /// </summary>
  268. /// <param name="msg"></param>
  269. void AddMsg(string msg)
  270. {
  271. if (this.lbxMsg.InvokeRequired)
  272. {
  273. // 很帅的调自己
  274. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  275. }
  276. else
  277. {
  278. if (this.lbxMsg.Items.Count > 100)
  279. {
  280. this.lbxMsg.Items.RemoveAt(0);
  281. }
  282. this.lbxMsg.Items.Add(msg);
  283. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  284. }
  285. }
  286. public delegate void SleepDelegate(int num);
  287. /// <summary>
  288. /// 精确延迟,摘自网络
  289. /// </summary>
  290. /// <param name="time"></param>
  291. private void Delay1(long time)
  292. {
  293. long b = DateTime.Now.Ticks / 10000;
  294. long e = 0; long c = 0; ;
  295. do
  296. {
  297. e = DateTime.Now.Ticks / 10000;
  298. c = e - b;
  299. Application.DoEvents();
  300. }
  301. while (c < time);
  302. }
  303. private void AsyncDelay(int time)
  304. {
  305. Thread.Sleep(time);
  306. }
  307. /// <summary>
  308. /// 精确延迟,摘自网络
  309. /// </summary>
  310. /// <param name="time"></param>
  311. private void Delay2(int time)
  312. {
  313. SleepDelegate delay = new SleepDelegate(AsyncDelay);
  314. IAsyncResult ar = delay.BeginInvoke(time, null, null);
  315. while (ar.IsCompleted == false)
  316. {
  317. Application.DoEvents();
  318. }
  319. delay.EndInvoke(ar);
  320. }
  321. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  322. {
  323. // 清理listbox
  324. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  325. {
  326. this.lbxMsg.Items.Clear();
  327. }
  328. }
  329. private void frmClient_FormClosing(object sender, FormClosingEventArgs e)
  330. {
  331. if (appState == AppState.Started)
  332. {
  333. btnStop_Click(sender, e);
  334. }
  335. }
  336. }
  337. }