frmServer.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. using System.Threading;
  12. namespace SSLServerNS
  13. {
  14. public enum AppState
  15. {
  16. Starting, Started, Stoping, Stoped, Error
  17. }
  18. public partial class frmServer : Form
  19. {
  20. private AppState appState = AppState.Stoped;
  21. private delegate void ShowMsg(string msg);
  22. private ShowMsg AddMsgDelegate;
  23. HPSocketCS.TcpServer server = new HPSocketCS.TcpServer();
  24. private static string title = "Echo-PFM Server [ 'C' - clear list box, 'R' - reset statics data ]";
  25. private long totalReceived = 0;
  26. private long totalSent = 0;
  27. private long clientCount = 0;
  28. public frmServer()
  29. {
  30. InitializeComponent();
  31. }
  32. private void Form1_Load(object sender, EventArgs e)
  33. {
  34. try
  35. {
  36. this.Text = title;
  37. // 本机测试没必要改地址,有需求请注释或删除
  38. this.txtIpAddress.ReadOnly = true;
  39. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  40. AddMsgDelegate = new ShowMsg(AddMsg);
  41. // 设置服务器事件
  42. server.OnPrepareListen += new TcpServerEvent.OnPrepareListenEventHandler(OnPrepareListen);
  43. server.OnAccept += new TcpServerEvent.OnAcceptEventHandler(OnAccept);
  44. server.OnSend += new TcpServerEvent.OnSendEventHandler(OnSend);
  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. Reset();
  65. server.IpAddress = ip;
  66. server.Port = port;
  67. // 启动服务
  68. if (server.Start())
  69. {
  70. this.Text = string.Format("{2} - ({0}:{1})", ip, port, title);
  71. SetAppState(AppState.Started);
  72. AddMsg(string.Format("$Server Start OK -> ({0}:{1})", ip, port));
  73. }
  74. else
  75. {
  76. SetAppState(AppState.Stoped);
  77. throw new Exception(string.Format("$Server Start Error -> {0}({1})", server.ErrorMessage, server.ErrorCode));
  78. }
  79. }
  80. catch (Exception ex)
  81. {
  82. AddMsg(ex.Message);
  83. }
  84. }
  85. private void btnStop_Click(object sender, EventArgs e)
  86. {
  87. SetAppState(AppState.Stoping);
  88. // 停止服务
  89. AddMsg("$Server Stop");
  90. if (server.Stop())
  91. {
  92. this.Text = title;
  93. SetAppState(AppState.Stoped);
  94. }
  95. else
  96. {
  97. AddMsg(string.Format("$Stop Error -> {0}({1})", server.ErrorMessage, server.ErrorCode));
  98. }
  99. }
  100. private void btnDisconn_Click(object sender, EventArgs e)
  101. {
  102. try
  103. {
  104. IntPtr connId = (IntPtr)Convert.ToUInt32(this.txtDisConn.Text.Trim());
  105. // 断开指定客户
  106. if (server.Disconnect(connId, true))
  107. {
  108. AddMsg(string.Format("$({0}) Disconnect OK", connId));
  109. }
  110. else
  111. {
  112. throw new Exception(string.Format("Disconnect({0}) Error", connId));
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. AddMsg(ex.Message);
  118. }
  119. }
  120. void Reset(bool isSetClientCount = true)
  121. {
  122. if (isSetClientCount)
  123. {
  124. clientCount = 0;
  125. }
  126. totalReceived = 0;
  127. totalSent = 0;
  128. }
  129. HandleResult OnPrepareListen(IntPtr soListen)
  130. {
  131. // 监听事件到达了,一般没什么用吧?
  132. return HandleResult.Ok;
  133. }
  134. HandleResult OnAccept(IntPtr connId, IntPtr pClient)
  135. {
  136. // 客户进入了
  137. if (clientCount == 0)
  138. {
  139. lock (title)
  140. {
  141. if (clientCount == 0)
  142. {
  143. Reset(false);
  144. }
  145. }
  146. }
  147. Interlocked.Increment(ref clientCount);
  148. // 获取客户端ip和端口
  149. string ip = string.Empty;
  150. ushort port = 0;
  151. if (server.GetRemoteAddress(connId, ref ip, ref port))
  152. {
  153. AddMsg(string.Format(" > [{0},OnAccept] -> PASS({1}:{2})", connId, ip.ToString(), port));
  154. }
  155. else
  156. {
  157. AddMsg(string.Format(" > [{0},OnAccept] -> Server_GetClientAddress() Error", connId));
  158. }
  159. return HandleResult.Ok;
  160. }
  161. HandleResult OnSend(IntPtr connId, byte[] bytes)
  162. {
  163. // 服务器发数据了
  164. Interlocked.Add(ref totalSent, bytes.Length);
  165. //AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", connId, length));
  166. return HandleResult.Ok;
  167. }
  168. HandleResult OnReceive(IntPtr connId, byte[] bytes)
  169. {
  170. // 数据到达了
  171. Interlocked.Add(ref totalReceived, bytes.Length);
  172. if (server.Send(connId, bytes, bytes.Length))
  173. {
  174. return HandleResult.Ok;
  175. }
  176. return HandleResult.Error;
  177. }
  178. HandleResult OnClose(IntPtr connId, SocketOperation enOperation, int errorCode)
  179. {
  180. if(errorCode == 0)
  181. AddMsg(string.Format(" > [{0},OnClose]", connId));
  182. else
  183. AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", connId, enOperation, errorCode));
  184. Calculate();
  185. return HandleResult.Ok;
  186. }
  187. HandleResult OnShutdown()
  188. {
  189. // 服务关闭了
  190. AddMsg(" > [OnShutdown]");
  191. return HandleResult.Ok;
  192. }
  193. void Calculate()
  194. {
  195. if(clientCount > 0)
  196. {
  197. lock(title)
  198. {
  199. if(clientCount > 0)
  200. {
  201. Interlocked.Decrement(ref clientCount);
  202. if(clientCount == 0)
  203. {
  204. //::WaitWithMessageLoop(600L);
  205. Thread tmpThread = new Thread(ShowTotalMsg);
  206. tmpThread.Start();
  207. }
  208. }
  209. }
  210. }
  211. }
  212. void ShowTotalMsg()
  213. {
  214. Thread.Sleep(600);
  215. AddMsg(string.Format(" *** Summary: send - {0}, recv - {1}", totalSent, totalReceived));
  216. }
  217. /// <summary>
  218. /// 设置程序状态
  219. /// </summary>
  220. /// <param name="state"></param>
  221. void SetAppState(AppState state)
  222. {
  223. appState = state;
  224. this.btnStart.Enabled = (appState == AppState.Stoped);
  225. this.btnStop.Enabled = (appState == AppState.Started);
  226. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  227. this.txtPort.Enabled = (appState == AppState.Stoped);
  228. this.txtDisConn.Enabled = (appState == AppState.Started);
  229. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  230. }
  231. /// <summary>
  232. /// 往listbox加一条项目
  233. /// </summary>
  234. /// <param name="msg"></param>
  235. void AddMsg(string msg)
  236. {
  237. if (this.lbxMsg.InvokeRequired)
  238. {
  239. // 很帅的调自己
  240. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  241. }
  242. else
  243. {
  244. if (this.lbxMsg.Items.Count > 100)
  245. {
  246. this.lbxMsg.Items.RemoveAt(0);
  247. }
  248. this.lbxMsg.Items.Add(msg);
  249. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  250. }
  251. }
  252. private void txtDisConn_TextChanged(object sender, EventArgs e)
  253. {
  254. // CONNID框被改变事件
  255. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  256. }
  257. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  258. {
  259. // 清理listbox
  260. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  261. {
  262. this.lbxMsg.Items.Clear();
  263. }
  264. else if (e.KeyChar == 'r' || e.KeyChar == 'R')
  265. {
  266. Reset();
  267. AddMsg(string.Format(" *** Reset Statics: CC - {0}, TS - {1}, TR - {2}", clientCount, totalSent, totalReceived));
  268. }
  269. }
  270. private void frmServer_FormClosed(object sender, FormClosedEventArgs e)
  271. {
  272. server.Destroy();
  273. }
  274. }
  275. [StructLayout(LayoutKind.Sequential)]
  276. public class ClientInfo
  277. {
  278. public uint ConnId { get; set; }
  279. public string IpAddress { get; set; }
  280. public ushort Port { get; set; }
  281. }
  282. }