frmServer.cs 10 KB

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