frmServer.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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.Runtime.InteropServices;
  10. using HPSocketCS;
  11. namespace SSLServerNS
  12. {
  13. public enum AppState
  14. {
  15. Starting, Started, Stoping, Stoped, Error
  16. }
  17. public partial class frmServer : Form
  18. {
  19. private AppState appState = AppState.Stoped;
  20. private delegate void ShowMsg(string msg);
  21. private ShowMsg AddMsgDelegate;
  22. HPSocketCS.TcpPackServer server = new HPSocketCS.TcpPackServer();
  23. private string title = "Echo TcpPackServer [ 'C' - clear list box ]";
  24. public frmServer()
  25. {
  26. InitializeComponent();
  27. }
  28. private void Form1_Load(object sender, EventArgs e)
  29. {
  30. try
  31. {
  32. this.Text = title;
  33. // 本机测试没必要改地址,有需求请注释或删除
  34. this.txtIpAddress.ReadOnly = true;
  35. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  36. AddMsgDelegate = new ShowMsg(AddMsg);
  37. // 设置服务器事件
  38. server.OnPrepareListen += new TcpServerEvent.OnPrepareListenEventHandler(OnPrepareListen);
  39. server.OnAccept += new TcpServerEvent.OnAcceptEventHandler(OnAccept);
  40. server.OnSend += new TcpServerEvent.OnSendEventHandler(OnSend);
  41. server.OnReceive += new TcpServerEvent.OnReceiveEventHandler(OnReceive);
  42. server.OnClose += new TcpServerEvent.OnCloseEventHandler(OnClose);
  43. server.OnShutdown += new TcpServerEvent.OnShutdownEventHandler(OnShutdown);
  44. // 设置包头标识,与对端设置保证一致性
  45. server.PackHeaderFlag = 0xff;
  46. // 设置最大封包大小
  47. server.MaxPackSize = 0x1000;
  48. SetAppState(AppState.Stoped);
  49. }
  50. catch (Exception ex)
  51. {
  52. SetAppState(AppState.Error);
  53. AddMsg(ex.Message);
  54. }
  55. }
  56. private void btnStart_Click(object sender, EventArgs e)
  57. {
  58. try
  59. {
  60. String ip = this.txtIpAddress.Text.Trim();
  61. ushort port = ushort.Parse(this.txtPort.Text.Trim());
  62. // 写在这个位置是上面可能会异常
  63. SetAppState(AppState.Starting);
  64. server.IpAddress = ip;
  65. server.Port = port;
  66. // 启动服务
  67. if (server.Start())
  68. {
  69. this.Text = string.Format("{2} - ({0}:{1})", ip, port, title);
  70. SetAppState(AppState.Started);
  71. AddMsg(string.Format("$Server Start OK -> ({0}:{1})", ip, port));
  72. }
  73. else
  74. {
  75. SetAppState(AppState.Stoped);
  76. throw new Exception(string.Format("$Server Start Error -> {0}({1})", server.ErrorMessage, server.ErrorCode));
  77. }
  78. }
  79. catch (Exception ex)
  80. {
  81. AddMsg(ex.Message);
  82. }
  83. }
  84. private void btnStop_Click(object sender, EventArgs e)
  85. {
  86. SetAppState(AppState.Stoping);
  87. // 停止服务
  88. AddMsg("$Server Stop");
  89. if (server.Stop())
  90. {
  91. this.Text = title;
  92. SetAppState(AppState.Stoped);
  93. }
  94. else
  95. {
  96. AddMsg(string.Format("$Stop Error -> {0}({1})", server.ErrorMessage, server.ErrorCode));
  97. }
  98. }
  99. private void btnDisconn_Click(object sender, EventArgs e)
  100. {
  101. try
  102. {
  103. IntPtr connId = (IntPtr)Convert.ToInt32(this.txtDisConn.Text.Trim());
  104. // 断开指定客户
  105. if (server.Disconnect(connId, true))
  106. {
  107. AddMsg(string.Format("$({0}) Disconnect OK", connId));
  108. }
  109. else
  110. {
  111. throw new Exception(string.Format("Disconnect({0}) Error", connId));
  112. }
  113. }
  114. catch (Exception ex)
  115. {
  116. AddMsg(ex.Message);
  117. }
  118. }
  119. HandleResult OnPrepareListen(IntPtr soListen)
  120. {
  121. // 监听事件到达了,一般没什么用吧?
  122. return HandleResult.Ok;
  123. }
  124. HandleResult OnAccept(IntPtr connId, IntPtr pClient)
  125. {
  126. // 客户进入了
  127. // 获取客户端ip和端口
  128. string ip = string.Empty;
  129. ushort port = 0;
  130. if (server.GetRemoteAddress(connId, ref ip, ref port))
  131. {
  132. AddMsg(string.Format(" > [{0},OnAccept] -> PASS({1}:{2})", connId, ip.ToString(), port));
  133. }
  134. else
  135. {
  136. AddMsg(string.Format(" > [{0},OnAccept] -> Server_GetClientAddress() Error", connId));
  137. }
  138. // 设置附加数据
  139. ClientInfo clientInfo = new ClientInfo();
  140. clientInfo.ConnId = connId;
  141. clientInfo.IpAddress = ip;
  142. clientInfo.Port = port;
  143. if (server.SetExtra(connId, clientInfo) == false)
  144. {
  145. AddMsg(string.Format(" > [{0},OnAccept] -> SetConnectionExtra fail", connId));
  146. }
  147. return HandleResult.Ok;
  148. }
  149. HandleResult OnSend(IntPtr connId, byte[] bytes)
  150. {
  151. // 服务器发数据了
  152. AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", connId, bytes.Length));
  153. return HandleResult.Ok;
  154. }
  155. HandleResult OnReceive(IntPtr connId, byte[] bytes)
  156. {
  157. // 数据到达了
  158. try
  159. {
  160. // 获取附加数据
  161. var clientInfo = server.GetExtra<ClientInfo>(connId);
  162. if (clientInfo != null)
  163. {
  164. // clientInfo 就是accept里传入的附加数据了
  165. AddMsg(string.Format(" > [{0},OnReceive] -> {1}:{2} ({3} bytes)", clientInfo.ConnId, clientInfo.IpAddress, clientInfo.Port, bytes.Length));
  166. }
  167. else
  168. {
  169. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", connId, bytes.Length));
  170. }
  171. if (server.Send(connId, bytes, bytes.Length))
  172. {
  173. return HandleResult.Ok;
  174. }
  175. return HandleResult.Error;
  176. }
  177. catch (Exception)
  178. {
  179. return HandleResult.Ignore;
  180. }
  181. }
  182. HandleResult OnClose(IntPtr connId, SocketOperation enOperation, int errorCode)
  183. {
  184. if(errorCode == 0)
  185. AddMsg(string.Format(" > [{0},OnClose]", connId));
  186. else
  187. AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", connId, enOperation, errorCode));
  188. // return HPSocketSdk.HandleResult.Ok;
  189. if (server.RemoveExtra(connId) == false)
  190. {
  191. AddMsg(string.Format(" > [{0},OnClose] -> SetConnectionExtra({0}, null) fail", connId));
  192. }
  193. return HandleResult.Ok;
  194. }
  195. HandleResult OnShutdown()
  196. {
  197. // 服务关闭了
  198. AddMsg(" > [OnShutdown]");
  199. return HandleResult.Ok;
  200. }
  201. /// <summary>
  202. /// 设置程序状态
  203. /// </summary>
  204. /// <param name="state"></param>
  205. void SetAppState(AppState state)
  206. {
  207. appState = state;
  208. this.btnStart.Enabled = (appState == AppState.Stoped);
  209. this.btnStop.Enabled = (appState == AppState.Started);
  210. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  211. this.txtPort.Enabled = (appState == AppState.Stoped);
  212. this.txtDisConn.Enabled = (appState == AppState.Started);
  213. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  214. }
  215. /// <summary>
  216. /// 往listbox加一条项目
  217. /// </summary>
  218. /// <param name="msg"></param>
  219. void AddMsg(string msg)
  220. {
  221. if (this.lbxMsg.InvokeRequired)
  222. {
  223. // 很帅的调自己
  224. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  225. }
  226. else
  227. {
  228. if (this.lbxMsg.Items.Count > 100)
  229. {
  230. this.lbxMsg.Items.RemoveAt(0);
  231. }
  232. this.lbxMsg.Items.Add(msg);
  233. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  234. }
  235. }
  236. private void txtDisConn_TextChanged(object sender, EventArgs e)
  237. {
  238. // CONNID框被改变事件
  239. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  240. }
  241. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  242. {
  243. // 清理listbox
  244. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  245. {
  246. this.lbxMsg.Items.Clear();
  247. }
  248. }
  249. private void frmServer_FormClosed(object sender, FormClosedEventArgs e)
  250. {
  251. server.Destroy();
  252. }
  253. }
  254. [StructLayout(LayoutKind.Sequential)]
  255. public class ClientInfo
  256. {
  257. public IntPtr ConnId { get; set; }
  258. public string IpAddress { get; set; }
  259. public ushort Port { get; set; }
  260. }
  261. }