frmClient.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 HPSocketCS;
  10. using System.Runtime.InteropServices;
  11. using System.IO;
  12. using System.Threading;
  13. namespace SSLClientNS
  14. {
  15. public enum AppState
  16. {
  17. Starting, Started, Stoping, Stoped, Error
  18. }
  19. public enum StudentType
  20. {
  21. None, Array, List, Single,
  22. }
  23. public partial class frmClient : Form
  24. {
  25. private AppState appState = AppState.Stoped;
  26. private delegate void ConnectUpdateUiDelegate();
  27. private delegate void SetAppStateDelegate(AppState state);
  28. private delegate void ShowMsg(string msg);
  29. private ShowMsg AddMsgDelegate;
  30. HPSocketCS.TcpPackClient client = new HPSocketCS.TcpPackClient();
  31. public frmClient()
  32. {
  33. InitializeComponent();
  34. }
  35. private void frmClient_Load(object sender, EventArgs e)
  36. {
  37. try
  38. {
  39. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  40. AddMsgDelegate = new ShowMsg(AddMsg);
  41. // 设置client事件
  42. client.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
  43. client.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
  44. client.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
  45. client.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
  46. client.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);
  47. // 设置包头标识,与对端设置保证一致性
  48. client.PackHeaderFlag = 0xff;
  49. // 设置最大封包大小
  50. client.MaxPackSize = 0x1000;
  51. SetAppState(AppState.Stoped);
  52. }
  53. catch (Exception ex)
  54. {
  55. SetAppState(AppState.Error);
  56. AddMsg(ex.Message);
  57. }
  58. }
  59. private void btnStart_Click(object sender, EventArgs e)
  60. {
  61. try
  62. {
  63. String ip = this.txtIpAddress.Text.Trim();
  64. ushort port = ushort.Parse(this.txtPort.Text.Trim());
  65. // 写在这个位置是上面可能会异常
  66. SetAppState(AppState.Starting);
  67. AddMsg(string.Format("$Client Starting ... -> ({0}:{1})", ip, port));
  68. if (client.Connect(ip, port, this.cbxAsyncConn.Checked))
  69. {
  70. if (cbxAsyncConn.Checked == false)
  71. {
  72. SetAppState(AppState.Started);
  73. }
  74. AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
  75. }
  76. else
  77. {
  78. SetAppState(AppState.Stoped);
  79. throw new Exception(string.Format("$Client Start Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  80. }
  81. }
  82. catch (Exception ex)
  83. {
  84. AddMsg(ex.Message);
  85. }
  86. }
  87. private void btnStop_Click(object sender, EventArgs e)
  88. {
  89. // 停止服务
  90. AddMsg("$Server Stop");
  91. if (client.Stop())
  92. {
  93. SetAppState(AppState.Stoped);
  94. }
  95. else
  96. {
  97. AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  98. }
  99. }
  100. private void btnSend_Click(object sender, EventArgs e)
  101. {
  102. try
  103. {
  104. string send = this.txtSend.Text;
  105. if (send.Length == 0)
  106. {
  107. return;
  108. }
  109. byte[] bytes = Encoding.Default.GetBytes(send);
  110. IntPtr connId = client.ConnectionId;
  111. // 发送
  112. if (client.Send(bytes, bytes.Length))
  113. {
  114. AddMsg(string.Format("$ ({0}) Send OK --> {1}", connId, send));
  115. }
  116. else
  117. {
  118. AddMsg(string.Format("$ ({0}) Send Fail --> {1} ({2})", connId, send, bytes.Length));
  119. }
  120. }
  121. catch (Exception ex)
  122. {
  123. AddMsg(string.Format("$ Send Fail --> msg ({0})", ex.Message));
  124. }
  125. }
  126. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  127. {
  128. // 清理listbox
  129. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  130. {
  131. this.lbxMsg.Items.Clear();
  132. }
  133. }
  134. void ConnectUpdateUi()
  135. {
  136. if (this.cbxAsyncConn.Checked == true)
  137. {
  138. SetAppState(AppState.Started);
  139. }
  140. }
  141. HandleResult OnPrepareConnect(TcpClient sender, uint socket)
  142. {
  143. return HandleResult.Ok;
  144. }
  145. HandleResult OnConnect(TcpClient sender)
  146. {
  147. // 已连接 到达一次
  148. // 如果是异步联接,更新界面状态
  149. this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));
  150. AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));
  151. return HandleResult.Ok;
  152. }
  153. HandleResult OnSend(TcpClient sender, byte[] bytes)
  154. {
  155. // 客户端发数据了
  156. AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", sender.ConnectionId, bytes.Length));
  157. return HandleResult.Ok;
  158. }
  159. HandleResult OnReceive(TcpClient sender, byte[] bytes)
  160. {
  161. // 数据到达了
  162. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, bytes.Length));
  163. return HandleResult.Ok;
  164. }
  165. HandleResult OnClose(TcpClient sender, SocketOperation enOperation, int errorCode)
  166. {
  167. if (errorCode == 0)
  168. // 连接关闭了
  169. AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));
  170. else
  171. // 出错了
  172. AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  173. // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
  174. // 生产环境请自己控制
  175. this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
  176. return HandleResult.Ok;
  177. }
  178. /// <summary>
  179. /// 设置程序状态
  180. /// </summary>
  181. /// <param name="state"></param>
  182. void SetAppState(AppState state)
  183. {
  184. appState = state;
  185. this.btnStart.Enabled = (appState == AppState.Stoped);
  186. this.btnStop.Enabled = (appState == AppState.Started);
  187. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  188. this.txtPort.Enabled = (appState == AppState.Stoped);
  189. this.cbxAsyncConn.Enabled = (appState == AppState.Stoped);
  190. this.btnSend.Enabled = (appState == AppState.Started);
  191. }
  192. /// <summary>
  193. /// 往listbox加一条项目
  194. /// </summary>
  195. /// <param name="msg"></param>
  196. void AddMsg(string msg)
  197. {
  198. if (this.lbxMsg.InvokeRequired)
  199. {
  200. // 很帅的调自己
  201. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  202. }
  203. else
  204. {
  205. if (this.lbxMsg.Items.Count > 100)
  206. {
  207. this.lbxMsg.Items.RemoveAt(0);
  208. }
  209. this.lbxMsg.Items.Add(msg);
  210. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  211. }
  212. }
  213. private void frmClient_FormClosed(object sender, FormClosedEventArgs e)
  214. {
  215. client.Destroy();
  216. }
  217. }
  218. }