frmServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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.TcpServer server = new HPSocketCS.TcpServer();
  23. HPSocketCS.Extra<ClientInfo> extra = new HPSocketCS.Extra<ClientInfo>();
  24. private string title = "Echo-TcpServer [ 'C' - clear list box ]";
  25. public frmServer()
  26. {
  27. InitializeComponent();
  28. }
  29. private void Form1_Load(object sender, EventArgs e)
  30. {
  31. try
  32. {
  33. this.Text = title;
  34. // 本机测试没必要改地址,有需求请注释或删除
  35. this.txtIpAddress.ReadOnly = true;
  36. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  37. AddMsgDelegate = new ShowMsg(AddMsg);
  38. // 设置服务器事件
  39. server.OnPrepareListen += new TcpServerEvent.OnPrepareListenEventHandler(OnPrepareListen);
  40. server.OnAccept += new TcpServerEvent.OnAcceptEventHandler(OnAccept);
  41. server.OnSend += new TcpServerEvent.OnSendEventHandler(OnSend);
  42. // 两个数据到达事件的一种
  43. server.OnPointerDataReceive += new TcpServerEvent.OnPointerDataReceiveEventHandler(OnPointerDataReceive);
  44. // 两个数据到达事件的一种
  45. //server.OnReceive += new TcpServerEvent.OnReceiveEventHandler(OnReceive);
  46. server.OnClose += new TcpServerEvent.OnCloseEventHandler(OnClose);
  47. server.OnShutdown += new TcpServerEvent.OnShutdownEventHandler(OnShutdown);
  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 (extra.Set(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 OnPointerDataReceive(IntPtr connId, IntPtr pData, int length)
  156. {
  157. // 数据到达了
  158. try
  159. {
  160. // 可以通过下面的方法转换到byte[]
  161. // byte[] bytes = new byte[length];
  162. // Marshal.Copy(pData, bytes, 0, length);
  163. // 获取附加数据
  164. ClientInfo clientInfo = extra.Get(connId);
  165. if (clientInfo != null)
  166. {
  167. // clientInfo 就是accept里传入的附加数据了
  168. AddMsg(string.Format(" > [{0},OnReceive] -> {1}:{2} ({3} bytes)", clientInfo.ConnId, clientInfo.IpAddress, clientInfo.Port, length));
  169. }
  170. else
  171. {
  172. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", connId, length));
  173. }
  174. if (server.Send(connId, pData, length))
  175. {
  176. return HandleResult.Ok;
  177. }
  178. return HandleResult.Error;
  179. }
  180. catch (Exception)
  181. {
  182. return HandleResult.Ignore;
  183. }
  184. }
  185. HandleResult OnReceive(IntPtr connId, byte[] bytes)
  186. {
  187. // 数据到达了
  188. try
  189. {
  190. // 获取附加数据
  191. ClientInfo clientInfo = extra.Get(connId);
  192. if (clientInfo != null)
  193. {
  194. // clientInfo 就是accept里传入的附加数据了
  195. AddMsg(string.Format(" > [{0},OnReceive] -> {1}:{2} ({3} bytes)", clientInfo.ConnId, clientInfo.IpAddress, clientInfo.Port, bytes.Length));
  196. }
  197. else
  198. {
  199. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", connId, bytes.Length));
  200. }
  201. if (server.Send(connId, bytes, bytes.Length))
  202. {
  203. return HandleResult.Ok;
  204. }
  205. return HandleResult.Error;
  206. }
  207. catch (Exception)
  208. {
  209. return HandleResult.Ignore;
  210. }
  211. }
  212. HandleResult OnClose(IntPtr connId, SocketOperation enOperation, int errorCode)
  213. {
  214. if (errorCode == 0)
  215. AddMsg(string.Format(" > [{0},OnClose]", connId));
  216. else
  217. AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", connId, enOperation, errorCode));
  218. if (extra.Remove(connId) == false)
  219. {
  220. AddMsg(string.Format(" > [{0},OnClose] -> SetConnectionExtra({0}, null) fail", connId));
  221. }
  222. return HandleResult.Ok;
  223. }
  224. HandleResult OnShutdown()
  225. {
  226. // 服务关闭了
  227. AddMsg(" > [OnShutdown]");
  228. return HandleResult.Ok;
  229. }
  230. /// <summary>
  231. /// 设置程序状态
  232. /// </summary>
  233. /// <param name="state"></param>
  234. void SetAppState(AppState state)
  235. {
  236. appState = state;
  237. this.btnStart.Enabled = (appState == AppState.Stoped);
  238. this.btnStop.Enabled = (appState == AppState.Started);
  239. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  240. this.txtPort.Enabled = (appState == AppState.Stoped);
  241. this.txtDisConn.Enabled = (appState == AppState.Started);
  242. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  243. }
  244. /// <summary>
  245. /// 往listbox加一条项目
  246. /// </summary>
  247. /// <param name="msg"></param>
  248. void AddMsg(string msg)
  249. {
  250. if (this.lbxMsg.InvokeRequired)
  251. {
  252. // 很帅的调自己
  253. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  254. }
  255. else
  256. {
  257. if (this.lbxMsg.Items.Count > 100)
  258. {
  259. this.lbxMsg.Items.RemoveAt(0);
  260. }
  261. this.lbxMsg.Items.Add(msg);
  262. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  263. }
  264. }
  265. private void txtDisConn_TextChanged(object sender, EventArgs e)
  266. {
  267. // CONNID框被改变事件
  268. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  269. }
  270. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  271. {
  272. // 清理listbox
  273. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  274. {
  275. this.lbxMsg.Items.Clear();
  276. }
  277. }
  278. private void frmServer_FormClosed(object sender, FormClosedEventArgs e)
  279. {
  280. server.Destroy();
  281. }
  282. }
  283. [StructLayout(LayoutKind.Sequential)]
  284. public class ClientInfo
  285. {
  286. public IntPtr ConnId { get; set; }
  287. public string IpAddress { get; set; }
  288. public ushort Port { get; set; }
  289. }
  290. }