frmServer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 TcpPullServer
  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.TcpPullServer server = new HPSocketCS.TcpPullServer();
  23. HPSocketCS.Extra<ClientInfo> extra = new HPSocketCS.Extra<ClientInfo>();
  24. // 包头大小
  25. int pkgHeaderSize = Marshal.SizeOf(new PkgHeader());
  26. private string title = "Echo-TcpPullServer [ 'C' - clear list box ]";
  27. public frmServer()
  28. {
  29. InitializeComponent();
  30. }
  31. private void Form1_Load(object sender, EventArgs e)
  32. {
  33. try
  34. {
  35. this.Text = title;
  36. // 本机测试没必要改地址,有需求请注释或删除
  37. this.txtIpAddress.ReadOnly = true;
  38. // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
  39. AddMsgDelegate = new ShowMsg(AddMsg);
  40. // 设置服务器事件
  41. server.OnPrepareListen += new TcpServerEvent.OnPrepareListenEventHandler(OnPrepareListen);
  42. server.OnAccept += new TcpServerEvent.OnAcceptEventHandler(OnAccept);
  43. server.OnSend += new TcpServerEvent.OnSendEventHandler(OnSend);
  44. server.OnReceive += new TcpPullServerEvent.OnReceiveEventHandler(OnReceive);
  45. server.OnClose += new TcpServerEvent.OnCloseEventHandler(OnClose);
  46. server.OnShutdown += new TcpServerEvent.OnShutdownEventHandler(OnShutdown);
  47. SetAppState(AppState.Stoped);
  48. }
  49. catch (Exception ex)
  50. {
  51. SetAppState(AppState.Error);
  52. AddMsg(ex.Message);
  53. }
  54. }
  55. private void btnStart_Click(object sender, EventArgs e)
  56. {
  57. try
  58. {
  59. String ip = this.txtIpAddress.Text.Trim();
  60. ushort port = ushort.Parse(this.txtPort.Text.Trim());
  61. // 写在这个位置是上面可能会异常
  62. SetAppState(AppState.Starting);
  63. server.IpAddress = ip;
  64. server.Port = port;
  65. // 启动服务
  66. if (server.Start())
  67. {
  68. this.Text = string.Format("{2} - ({0}:{1})", ip, port, title);
  69. SetAppState(AppState.Started);
  70. AddMsg(string.Format("$Server Start OK -> ({0}:{1})", ip, port));
  71. }
  72. else
  73. {
  74. SetAppState(AppState.Stoped);
  75. throw new Exception(string.Format("$Server Start Error -> {0}({1})", server.ErrorMessage, server.ErrorCode));
  76. }
  77. }
  78. catch (Exception ex)
  79. {
  80. AddMsg(ex.Message);
  81. }
  82. }
  83. private void btnStop_Click(object sender, EventArgs e)
  84. {
  85. SetAppState(AppState.Stoping);
  86. // 停止服务
  87. AddMsg("$Server Stop");
  88. if (server.Stop())
  89. {
  90. this.Text = title;
  91. SetAppState(AppState.Stoped);
  92. }
  93. else
  94. {
  95. AddMsg(string.Format("$Stop Error -> {0}({1})", server.ErrorMessage, server.ErrorCode));
  96. }
  97. }
  98. private void btnDisconn_Click(object sender, EventArgs e)
  99. {
  100. try
  101. {
  102. IntPtr connId = (IntPtr)Convert.ToUInt32(this.txtDisConn.Text.Trim());
  103. // 断开指定客户
  104. if (server.Disconnect(connId, true))
  105. {
  106. AddMsg(string.Format("$({0}) Disconnect OK", connId));
  107. }
  108. else
  109. {
  110. throw new Exception(string.Format("Disconnect({0}) Error", connId));
  111. }
  112. }
  113. catch (Exception ex)
  114. {
  115. AddMsg(ex.Message);
  116. }
  117. }
  118. HandleResult OnPrepareListen(IntPtr soListen)
  119. {
  120. // 监听事件到达了,一般没什么用吧?
  121. return HandleResult.Ok;
  122. }
  123. HandleResult OnAccept(IntPtr connId, IntPtr pClient)
  124. {
  125. // 客户进入了
  126. // 获取客户端ip和端口
  127. string ip = string.Empty;
  128. ushort port = 0;
  129. if (server.GetRemoteAddress(connId, ref ip, ref port))
  130. {
  131. AddMsg(string.Format(" > [{0},OnAccept] -> PASS({1}:{2})", connId, ip.ToString(), port));
  132. }
  133. else
  134. {
  135. AddMsg(string.Format(" > [{0},OnAccept] -> Server_GetClientAddress() Error", connId));
  136. }
  137. // 设置附加数据
  138. ClientInfo clientInfo = new ClientInfo();
  139. clientInfo.ConnId = connId;
  140. clientInfo.IpAddress = ip;
  141. clientInfo.Port = port;
  142. clientInfo.PkgInfo = new PkgInfo()
  143. {
  144. IsHeader = true,
  145. Length = pkgHeaderSize,
  146. };
  147. if (extra.Set(connId, clientInfo) == false)
  148. {
  149. AddMsg(string.Format(" > [{0},OnAccept] -> SetConnectionExtra fail", connId));
  150. }
  151. return HandleResult.Ok;
  152. }
  153. HandleResult OnSend(IntPtr connId, byte[] bytes)
  154. {
  155. // 服务器发数据了
  156. AddMsg(string.Format(" > [{0},OnSend] -> ({1} bytes)", connId, bytes.Length));
  157. return HandleResult.Ok;
  158. }
  159. HandleResult OnReceive(IntPtr connId, int length)
  160. {
  161. // 数据到达了
  162. // clientInfo 就是accept里传入的附加数据了
  163. ClientInfo clientInfo = extra.Get(connId);
  164. if (clientInfo == null)
  165. {
  166. return HandleResult.Error;
  167. }
  168. PkgInfo pkgInfo = clientInfo.PkgInfo;
  169. // 需要长度
  170. int required = pkgInfo.Length;
  171. // 剩余大小
  172. int remain = length;
  173. while (remain >= required)
  174. {
  175. IntPtr bufferPtr = IntPtr.Zero;
  176. try
  177. {
  178. remain -= required;
  179. bufferPtr = Marshal.AllocHGlobal(required); ;
  180. if (server.Fetch(connId, bufferPtr, required) == FetchResult.Ok)
  181. {
  182. if (pkgInfo.IsHeader == true)
  183. {
  184. PkgHeader header = (PkgHeader)Marshal.PtrToStructure(bufferPtr, typeof(PkgHeader));
  185. // 调试信息
  186. Console.WriteLine("[Server] head -> Id: {0}, BodySize: {1}\r\n", header.Id, header.BodySize);
  187. required = header.BodySize;
  188. }
  189. else
  190. {
  191. // 调试信息
  192. string recvString = Marshal.PtrToStringAnsi(bufferPtr, required);
  193. Console.WriteLine("[Server] body -> text: {0}\r\n", recvString);
  194. // intptr转string
  195. //Marshal.PtrToStringAnsi(bufferPtr, required);
  196. //intptr转byte[]
  197. // byte[] bytes = new byte[required];
  198. // Marshal.Copy(bufferPtr, bytes, 0, required);
  199. required = pkgHeaderSize;
  200. }
  201. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", connId, pkgInfo.Length));
  202. // 回发数据
  203. byte[] sendBytes = new byte[pkgInfo.Length];
  204. Marshal.Copy(bufferPtr, sendBytes, 0, sendBytes.Length);
  205. if (server.Send(connId, sendBytes, sendBytes.Length) == false)
  206. {
  207. throw new Exception("server.Send() == false");
  208. }
  209. // 在后面赋值,因为前面需要用到pkgInfo.Length
  210. pkgInfo.IsHeader = !pkgInfo.IsHeader;
  211. pkgInfo.Length = required;
  212. if (extra.Set(connId, clientInfo) == false)
  213. {
  214. return HandleResult.Error;
  215. }
  216. }
  217. }
  218. catch
  219. {
  220. return HandleResult.Error;
  221. }
  222. finally
  223. {
  224. if (bufferPtr != IntPtr.Zero)
  225. {
  226. Marshal.FreeHGlobal(bufferPtr);
  227. bufferPtr = IntPtr.Zero;
  228. }
  229. }
  230. }
  231. return HandleResult.Ok;
  232. }
  233. HandleResult OnClose(IntPtr connId, SocketOperation enOperation, int errorCode)
  234. {
  235. if(errorCode == 0)
  236. // 客户离开了
  237. AddMsg(string.Format(" > [{0},OnClose]", connId));
  238. else
  239. // 客户出错了
  240. AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", connId, enOperation, errorCode));
  241. // return HPSocketSdk.HandleResult.Ok;
  242. // 释放附加数据
  243. if (extra.Remove(connId) == false)
  244. {
  245. AddMsg(string.Format(" > [{0},OnClose] -> SetConnectionExtra({0}, null) fail", connId));
  246. }
  247. return HandleResult.Ok;
  248. }
  249. HandleResult OnShutdown()
  250. {
  251. // 服务关闭了
  252. AddMsg(" > [OnShutdown]");
  253. return HandleResult.Ok;
  254. }
  255. /// <summary>
  256. /// 设置程序状态
  257. /// </summary>
  258. /// <param name="state"></param>
  259. void SetAppState(AppState state)
  260. {
  261. appState = state;
  262. this.btnStart.Enabled = (appState == AppState.Stoped);
  263. this.btnStop.Enabled = (appState == AppState.Started);
  264. this.txtIpAddress.Enabled = (appState == AppState.Stoped);
  265. this.txtPort.Enabled = (appState == AppState.Stoped);
  266. this.txtDisConn.Enabled = (appState == AppState.Started);
  267. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  268. }
  269. /// <summary>
  270. /// 往listbox加一条项目
  271. /// </summary>
  272. /// <param name="msg"></param>
  273. void AddMsg(string msg)
  274. {
  275. if (this.lbxMsg.InvokeRequired)
  276. {
  277. // 很帅的调自己
  278. this.lbxMsg.Invoke(AddMsgDelegate, msg);
  279. }
  280. else
  281. {
  282. if (this.lbxMsg.Items.Count > 100)
  283. {
  284. this.lbxMsg.Items.RemoveAt(0);
  285. }
  286. this.lbxMsg.Items.Add(msg);
  287. this.lbxMsg.TopIndex = this.lbxMsg.Items.Count - (int)(this.lbxMsg.Height / this.lbxMsg.ItemHeight);
  288. }
  289. }
  290. private void txtDisConn_TextChanged(object sender, EventArgs e)
  291. {
  292. // CONNID框被改变事件
  293. this.btnDisconn.Enabled = (appState == AppState.Started && this.txtDisConn.Text.Length > 0);
  294. }
  295. private void lbxMsg_KeyPress(object sender, KeyPressEventArgs e)
  296. {
  297. // 清理listbox
  298. if (e.KeyChar == 'c' || e.KeyChar == 'C')
  299. {
  300. this.lbxMsg.Items.Clear();
  301. }
  302. }
  303. private void frmServer_FormClosed(object sender, FormClosedEventArgs e)
  304. {
  305. server.Destroy();
  306. }
  307. }
  308. [StructLayout(LayoutKind.Sequential)]
  309. public class ClientInfo
  310. {
  311. public IntPtr ConnId { get; set; }
  312. public string IpAddress { get; set; }
  313. public ushort Port { get; set; }
  314. public PkgInfo PkgInfo { get; set; }
  315. }
  316. [StructLayout(LayoutKind.Sequential)]
  317. public class PkgHeader
  318. {
  319. public int Id;
  320. public int BodySize;
  321. }
  322. [StructLayout(LayoutKind.Sequential)]
  323. public class PkgInfo
  324. {
  325. public bool IsHeader;
  326. public int Length;
  327. }
  328. }