TcpServer.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. using System.IO;
  7. using System.Runtime.Serialization.Formatters.Binary;
  8. using System.Runtime.Serialization;
  9. namespace HPSocketCS
  10. {
  11. public class TcpServerEvent
  12. {
  13. public delegate HandleResult OnSendEventHandler(IntPtr connId, byte[] bytes);
  14. public delegate HandleResult OnReceiveEventHandler(IntPtr connId, byte[] bytes);
  15. public delegate HandleResult OnPointerDataReceiveEventHandler(IntPtr connId, IntPtr pData, int length);
  16. public delegate HandleResult OnCloseEventHandler(IntPtr connId, SocketOperation enOperation, int errorCode);
  17. public delegate HandleResult OnShutdownEventHandler();
  18. public delegate HandleResult OnPrepareListenEventHandler(IntPtr soListen);
  19. public delegate HandleResult OnAcceptEventHandler(IntPtr connId, IntPtr pClient);
  20. }
  21. public class TcpServer : ConnectionExtra
  22. {
  23. protected IntPtr _pServer = IntPtr.Zero;
  24. protected IntPtr pServer
  25. {
  26. get
  27. {
  28. return _pServer;
  29. }
  30. set
  31. {
  32. _pServer = value;
  33. }
  34. }
  35. protected IntPtr pListener = IntPtr.Zero;
  36. /// <summary>
  37. /// 服务器ip
  38. /// </summary>
  39. public string IpAddress { get; set; }
  40. /// <summary>
  41. /// 服务器端口
  42. /// </summary>
  43. public ushort Port { get; set; }
  44. /// <summary>
  45. /// 连接到达事件
  46. /// </summary>
  47. public event TcpServerEvent.OnAcceptEventHandler OnAccept;
  48. /// <summary>
  49. /// 数据包发送事件
  50. /// </summary>
  51. public event TcpServerEvent.OnSendEventHandler OnSend;
  52. /// <summary>
  53. /// 准备监听了事件
  54. /// </summary>
  55. public event TcpServerEvent.OnPrepareListenEventHandler OnPrepareListen;
  56. /// <summary>
  57. /// 数据到达事件
  58. /// </summary>
  59. public event TcpServerEvent.OnReceiveEventHandler OnReceive;
  60. /// <summary>
  61. /// 数据到达事件(指针数据)
  62. /// </summary>
  63. public event TcpServerEvent.OnPointerDataReceiveEventHandler OnPointerDataReceive;
  64. /// <summary>
  65. /// 连接关闭事件
  66. /// </summary>
  67. public event TcpServerEvent.OnCloseEventHandler OnClose;
  68. /// <summary>
  69. /// 服务器关闭事件
  70. /// </summary>
  71. public event TcpServerEvent.OnShutdownEventHandler OnShutdown;
  72. protected bool IsCreate = false;
  73. /// <summary>
  74. /// tcpserver构造
  75. /// </summary>
  76. public TcpServer()
  77. {
  78. CreateListener();
  79. }
  80. ~TcpServer()
  81. {
  82. Destroy();
  83. }
  84. /// <summary>
  85. /// 创建socket监听&服务组件
  86. /// </summary>
  87. /// <param name="isUseDefaultCallback">是否使用tcpserver类默认回调函数</param>
  88. /// <returns></returns>
  89. protected virtual bool CreateListener()
  90. {
  91. if (IsCreate == true || pListener != IntPtr.Zero || pServer != IntPtr.Zero)
  92. {
  93. return false;
  94. }
  95. pListener = Sdk.Create_HP_TcpServerListener();
  96. if (pListener == IntPtr.Zero)
  97. {
  98. return false;
  99. }
  100. pServer = Sdk.Create_HP_TcpServer(pListener);
  101. if (pServer == IntPtr.Zero)
  102. {
  103. return false;
  104. }
  105. IsCreate = true;
  106. return true;
  107. }
  108. /// <summary>
  109. /// 终止服务并释放资源
  110. /// </summary>
  111. public virtual void Destroy()
  112. {
  113. Stop();
  114. if (pServer != IntPtr.Zero)
  115. {
  116. Sdk.Destroy_HP_TcpServer(pServer);
  117. pServer = IntPtr.Zero;
  118. }
  119. if (pListener != IntPtr.Zero)
  120. {
  121. Sdk.Destroy_HP_TcpServerListener(pListener);
  122. pListener = IntPtr.Zero;
  123. }
  124. IsCreate = false;
  125. }
  126. /// <summary>
  127. /// 启动服务
  128. /// </summary>
  129. /// <param name="address"></param>
  130. /// <param name="port"></param>
  131. /// <returns></returns>
  132. public bool Start()
  133. {
  134. if (IsCreate == false)
  135. {
  136. return false;
  137. }
  138. if (IsStarted == true)
  139. {
  140. return false;
  141. }
  142. SetCallback();
  143. return Sdk.HP_Server_Start(pServer, IpAddress, Port);
  144. }
  145. /// <summary>
  146. /// 停止服务
  147. /// </summary>
  148. /// <returns></returns>
  149. public bool Stop()
  150. {
  151. if (IsStarted == false)
  152. {
  153. return false;
  154. }
  155. return Sdk.HP_Server_Stop(pServer);
  156. }
  157. /// <summary>
  158. /// 发送数据
  159. /// </summary>
  160. /// <param name="connId"></param>
  161. /// <param name="bytes"></param>
  162. /// <param name="size"></param>
  163. /// <returns></returns>
  164. public bool Send(IntPtr connId, byte[] bytes, int size)
  165. {
  166. return Sdk.HP_Server_Send(pServer, connId, bytes, size);
  167. }
  168. /// <summary>
  169. /// 发送数据
  170. /// </summary>
  171. /// <param name="connId"></param>
  172. /// <param name="bufferPtr"></param>
  173. /// <param name="size"></param>
  174. /// <returns></returns>
  175. public bool Send(IntPtr connId, IntPtr bufferPtr, int size)
  176. {
  177. return Sdk.HP_Server_Send(pServer, connId, bufferPtr, size);
  178. }
  179. /// <summary>
  180. /// 发送数据
  181. /// </summary>
  182. /// <param name="connId"></param>
  183. /// <param name="bytes"></param>
  184. /// <param name="offset">针对bytes的偏移</param>
  185. /// <param name="size">发多大</param>
  186. /// <returns></returns>
  187. public bool Send(IntPtr connId, byte[] bytes, int offset, int size)
  188. {
  189. return Sdk.HP_Server_SendPart(pServer, connId, bytes, size, offset);
  190. }
  191. /// <summary>
  192. /// 发送数据
  193. /// </summary>
  194. /// <param name="connId"></param>
  195. /// <param name="bufferPtr"></param>
  196. /// <param name="offset">针对bufferPtr的偏移</param>
  197. /// <param name="size">发多大</param>
  198. /// <returns></returns>
  199. public bool Send(IntPtr connId, IntPtr bufferPtr, int offset, int size)
  200. {
  201. return Sdk.HP_Server_SendPart(pServer, connId, bufferPtr, size, offset);
  202. }
  203. /// <summary>
  204. /// 发送数据
  205. /// </summary>
  206. /// <param name="connId"></param>
  207. /// <param name="bufferPtr"></param>
  208. /// <param name="size"></param>
  209. /// <returns></returns>
  210. public bool Send<T>(IntPtr connId, T obj)
  211. {
  212. byte[] buffer = StructureToByte<T>(obj);
  213. return Send(connId, buffer, buffer.Length);
  214. }
  215. /// <summary>
  216. /// 序列化对象后发送数据,序列化对象所属类必须标记[Serializable]
  217. /// </summary>
  218. /// <param name="connId"></param>
  219. /// <param name="bufferPtr"></param>
  220. /// <param name="size"></param>
  221. /// <returns></returns>
  222. public bool SendBySerializable(IntPtr connId, object obj)
  223. {
  224. byte[] buffer = ObjectToBytes(obj);
  225. return Send(connId, buffer, buffer.Length);
  226. }
  227. /// <summary>
  228. /// 发送多组数据
  229. /// 向指定连接发送多组数据
  230. /// TCP - 顺序发送所有数据包
  231. /// </summary>
  232. /// <param name="connId">连接 ID</param>
  233. /// <param name="pBuffers">发送缓冲区数组</param>
  234. /// <param name="iCount">发送缓冲区数目</param>
  235. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  236. public bool SendPackets(IntPtr connId, WSABUF[] pBuffers, int count)
  237. {
  238. return Sdk.HP_Server_SendPackets(pServer, connId, pBuffers, count);
  239. }
  240. /// <summary>
  241. /// 发送多组数据
  242. /// 向指定连接发送多组数据
  243. /// TCP - 顺序发送所有数据包
  244. /// </summary>
  245. /// <param name="connId">连接 ID</param>
  246. /// <param name="pBuffers">发送缓冲区数组</param>
  247. /// <param name="iCount">发送缓冲区数目</param>
  248. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  249. public bool SendPackets<T>(IntPtr connId, T[] objects)
  250. {
  251. bool ret = false;
  252. WSABUF[] buffer = new WSABUF[objects.Length];
  253. IntPtr[] ptrs = new IntPtr[buffer.Length];
  254. try
  255. {
  256. for (int i = 0; i < objects.Length; i++)
  257. {
  258. buffer[i].Length = Marshal.SizeOf(typeof(T));
  259. ptrs[i] = Marshal.AllocHGlobal(buffer[i].Length);
  260. Marshal.StructureToPtr(objects[i], ptrs[i], true);
  261. buffer[i].Buffer = ptrs[i];
  262. }
  263. ret = SendPackets(connId, buffer, buffer.Length);
  264. }
  265. catch (Exception ex)
  266. {
  267. throw ex;
  268. }
  269. finally
  270. {
  271. for (int i = 0; i < ptrs.Length; i++)
  272. {
  273. if (ptrs[i] != IntPtr.Zero)
  274. {
  275. Marshal.FreeHGlobal(ptrs[i]);
  276. }
  277. }
  278. }
  279. return ret;
  280. }
  281. /// <summary>
  282. /// 名称:发送小文件
  283. /// 描述:向指定连接发送 4096 KB 以下的小文件
  284. /// </summary>
  285. /// <param name="connId"></param>
  286. /// <param name="filePath">文件路径</param>
  287. /// <param name="head">头部附加数据</param>
  288. /// <param name="tail">尾部附加数据</param>
  289. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  290. public bool SendSmallFile(IntPtr connId, string filePath, ref WSABUF head, ref WSABUF tail)
  291. {
  292. return Sdk.HP_TcpServer_SendSmallFile(pServer, connId, filePath, ref head, ref tail);
  293. }
  294. /// <summary>
  295. /// 名称:发送小文件
  296. /// 描述:向指定连接发送 4096 KB 以下的小文件
  297. /// </summary>
  298. /// <param name="connId"></param>
  299. /// <param name="filePath">文件路径</param>
  300. /// <param name="head">头部附加数据,可以为null</param>
  301. /// <param name="tail">尾部附加数据,可以为null</param>
  302. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  303. public bool SendSmallFile(IntPtr connId, string filePath, byte[] head, byte[] tail)
  304. {
  305. IntPtr pHead = IntPtr.Zero;
  306. IntPtr pTail = IntPtr.Zero;
  307. WSABUF wsaHead = new WSABUF() { Length = 0, Buffer = pHead };
  308. WSABUF wsatail = new WSABUF() { Length = 0, Buffer = pTail };
  309. if (head != null)
  310. {
  311. wsaHead.Length = head.Length;
  312. wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(head, 0);
  313. }
  314. if (tail != null)
  315. {
  316. wsaHead.Length = tail.Length;
  317. wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(tail, 0);
  318. }
  319. return SendSmallFile(connId, filePath, ref wsaHead, ref wsatail);
  320. }
  321. /// <summary>
  322. /// 名称:发送小文件
  323. /// 描述:向指定连接发送 4096 KB 以下的小文件
  324. /// </summary>
  325. /// <param name="connId"></param>
  326. /// <param name="filePath">文件路径</param>
  327. /// <param name="head">头部附加数据,可以为null</param>
  328. /// <param name="tail">尾部附加数据,可以为null</param>
  329. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  330. public bool SendSmallFile<T1, T2>(IntPtr connId, string filePath, T1 head, T2 tail)
  331. {
  332. byte[] headBuffer = null;
  333. if (head != null)
  334. {
  335. headBuffer = StructureToByte<T1>(head);
  336. }
  337. byte[] tailBuffer = null;
  338. if (tail != null)
  339. {
  340. tailBuffer = StructureToByte<T2>(tail);
  341. }
  342. return SendSmallFile(connId, filePath, headBuffer, tailBuffer);
  343. }
  344. /// <summary>
  345. /// 断开与某个客户的连接
  346. /// </summary>
  347. /// <param name="connId"></param>
  348. /// <param name="bForce">是否强制断开</param>
  349. /// <returns></returns>
  350. public bool Disconnect(IntPtr connId, bool force = true)
  351. {
  352. return Sdk.HP_Server_Disconnect(pServer, connId, force);
  353. }
  354. /// <summary>
  355. /// 断开超过指定时间的连接
  356. /// </summary>
  357. /// <param name="period">毫秒</param>
  358. /// <param name="force">强制</param>
  359. /// <returns></returns>
  360. public bool DisconnectLongConnections(uint period, bool force = true)
  361. {
  362. return Sdk.HP_Server_DisconnectLongConnections(pServer, period, force);
  363. }
  364. /// <summary>
  365. /// 断开超过指定时长的静默连接
  366. /// </summary>
  367. /// <param name="period">毫秒</param>
  368. /// <param name="force">强制</param>
  369. /// <returns></returns>
  370. public bool DisconnectSilenceConnections(uint period, bool force = true)
  371. {
  372. return Sdk.HP_Server_DisconnectSilenceConnections(pServer, period, force);
  373. }
  374. /// <summary>
  375. /// 获取某个连接的本地地址信息
  376. /// </summary>
  377. /// <param name="connId"></param>
  378. /// <param name="ip"></param>
  379. /// <param name="port"></param>
  380. /// <returns></returns>
  381. public bool GetLocalAddress(IntPtr connId, ref string ip, ref ushort port)
  382. {
  383. int ipLength = 40;
  384. StringBuilder sb = new StringBuilder(ipLength);
  385. bool ret = Sdk.HP_Server_GetLocalAddress(pServer, connId, sb, ref ipLength, ref port) && ipLength > 0;
  386. if (ret == true)
  387. {
  388. ip = sb.ToString();
  389. }
  390. return ret;
  391. }
  392. /// <summary>
  393. /// 获取某个连接的远程地址信息
  394. /// </summary>
  395. /// <param name="connId"></param>
  396. /// <param name="ip"></param>
  397. /// <param name="port"></param>
  398. /// <returns></returns>
  399. public bool GetRemoteAddress(IntPtr connId, ref string ip, ref ushort port)
  400. {
  401. int ipLength = 40;
  402. StringBuilder sb = new StringBuilder(ipLength);
  403. bool ret = Sdk.HP_Server_GetRemoteAddress(pServer, connId, sb, ref ipLength, ref port) && ipLength > 0;
  404. if (ret == true)
  405. {
  406. ip = sb.ToString();
  407. }
  408. return ret;
  409. }
  410. /// <summary>
  411. /// 获取连接中未发出数据的长度
  412. /// </summary>
  413. /// <param name="connId"></param>
  414. /// <param name="length"></param>
  415. /// <returns></returns>
  416. public bool GetPendingDataLength(IntPtr connId, ref int length)
  417. {
  418. return Sdk.HP_Server_GetPendingDataLength(pServer, connId, ref length);
  419. }
  420. ///// <summary>
  421. ///// 设置连接的附加数据
  422. ///// </summary>
  423. ///// <param name="connId"></param>
  424. ///// <param name="obj">如果为null,则为释放设置的数据</param>
  425. ///// <returns></returns>
  426. //public bool SetConnectionExtra(IntPtr connId, object obj)
  427. //{
  428. // IntPtr ptr = IntPtr.Zero;
  429. // // 释放附加数据
  430. // if (Sdk.HP_Server_GetConnectionExtra(pServer, connId, ref ptr) && ptr != IntPtr.Zero)
  431. // {
  432. // Marshal.FreeHGlobal(ptr);
  433. // ptr = IntPtr.Zero;
  434. // }
  435. // if (obj != null)
  436. // {
  437. // // 设置附加数据
  438. // ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));
  439. // Marshal.StructureToPtr(obj, ptr, false);
  440. // }
  441. // return Sdk.HP_Server_SetConnectionExtra(pServer, connId, ptr);
  442. //}
  443. ///// <summary>
  444. ///// 获取附加数据
  445. ///// 如设置的是个结构体/类对象,可以用 Type objA = (Type)Marshal.PtrToStructure(ptr, typeof(Type)) 获取
  446. ///// 其中Type是结构体/类名,ptr是该方法的传出值,在该方法返回为true的时候可用
  447. ///// </summary>
  448. ///// <param name="connId"></param>
  449. ///// <param name="ptr"></param>
  450. ///// <returns></returns>
  451. //[Obsolete("该非泛型方法已过期,推荐使用泛型方法: T GetConnectionExtra<T>(IntPtr connId)")]
  452. //public bool GetConnectionExtra(IntPtr connId, ref IntPtr ptr)
  453. //{
  454. // return Sdk.HP_Server_GetConnectionExtra(pServer, connId, ref ptr) && ptr != IntPtr.Zero;
  455. //}
  456. ///// <summary>
  457. ///// 获取附加数据
  458. ///// 成功时返回对象,失败时返回T类型默认值,如:int=0, classA=null
  459. ///// </summary>
  460. ///// <param name="connId"></param>
  461. ///// <returns></returns>
  462. //public T GetConnectionExtra<T>(IntPtr connId)
  463. //{
  464. // IntPtr ptr = IntPtr.Zero;
  465. // T obj = default(T);
  466. // if (Sdk.HP_Server_GetConnectionExtra(pServer, connId, ref ptr))
  467. // {
  468. // obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
  469. // }
  470. // return obj;
  471. //}
  472. ///// <summary>
  473. ///// 移除连接中的附加数据, 同SetConnectionExtra(id, null)
  474. ///// </summary>
  475. ///// <param name="connId"></param>
  476. ///// <returns></returns>
  477. //public bool RemoveConnectionExtra(IntPtr connId)
  478. //{
  479. // return SetConnectionExtra(connId, null);
  480. //}
  481. // 是否启动
  482. public bool IsStarted
  483. {
  484. get
  485. {
  486. if (pServer == IntPtr.Zero)
  487. {
  488. return false;
  489. }
  490. return Sdk.HP_Server_HasStarted(pServer);
  491. }
  492. }
  493. /// <summary>
  494. /// 状态
  495. /// </summary>
  496. public ServiceState State
  497. {
  498. get
  499. {
  500. return Sdk.HP_Server_GetState(pServer);
  501. }
  502. }
  503. /// <summary>
  504. /// 连接数
  505. /// </summary>
  506. public uint ConnectionCount
  507. {
  508. get
  509. {
  510. return Sdk.HP_Server_GetConnectionCount(pServer);
  511. }
  512. }
  513. /// <summary>
  514. /// 获取所有连接,未获取到连接返回null
  515. /// </summary>
  516. /// <returns></returns>
  517. public IntPtr[] GetAllConnectionIDs()
  518. {
  519. IntPtr[] arr = null;
  520. do
  521. {
  522. uint count = ConnectionCount;
  523. if (count == 0)
  524. {
  525. break;
  526. }
  527. arr = new IntPtr[count];
  528. if (Sdk.HP_Server_GetAllConnectionIDs(pServer, arr, ref count))
  529. {
  530. if (arr.Length > count)
  531. {
  532. IntPtr[] newArr = new IntPtr[count];
  533. Array.Copy(arr, newArr, count);
  534. arr = newArr;
  535. }
  536. break;
  537. }
  538. } while (true);
  539. return arr;
  540. }
  541. /// <summary>
  542. /// 获取监听socket的地址信息
  543. /// </summary>
  544. /// <param name="ip"></param>
  545. /// <param name="port"></param>
  546. /// <returns></returns>
  547. public bool GetListenAddress(ref string ip, ref ushort port)
  548. {
  549. int ipLength = 40;
  550. StringBuilder sb = new StringBuilder(ipLength);
  551. bool ret = Sdk.HP_Server_GetListenAddress(pServer, sb, ref ipLength, ref port);
  552. if (ret == true)
  553. {
  554. ip = sb.ToString();
  555. }
  556. return ret;
  557. }
  558. /// <summary>
  559. /// 获取指定连接的连接时长(毫秒)
  560. /// </summary>
  561. /// <param name="connId"></param>
  562. /// <param name="period"></param>
  563. /// <returns></returns>
  564. public bool GetConnectPeriod(IntPtr connId, ref uint period)
  565. {
  566. return Sdk.HP_Server_GetConnectPeriod(pServer, connId, ref period);
  567. }
  568. /// <summary>
  569. /// 获取某个连接静默时间(毫秒)
  570. /// </summary>
  571. /// <param name="connId"></param>
  572. /// <param name="period"></param>
  573. /// <returns></returns>
  574. public bool GetSilencePeriod(IntPtr connId, ref uint period)
  575. {
  576. return Sdk.HP_Server_GetSilencePeriod(pServer, connId, ref period);
  577. }
  578. ///////////////////////////////////////////////////////////////////////////////////////
  579. /// <summary>
  580. /// 设置最大连接数(组件会根据设置值预分配内存,因此需要根据实际情况设置,不宜过大)
  581. /// </summary>
  582. public uint MaxConnectionCount
  583. {
  584. get
  585. {
  586. return Sdk.HP_Server_GetMaxConnectionCount(pServer);
  587. }
  588. set
  589. {
  590. Sdk.HP_Server_SetMaxConnectionCount(pServer, value);
  591. }
  592. }
  593. /// <summary>
  594. /// 读取或设置工作线程数量(通常设置为 2 * CPU + 2)
  595. /// </summary>
  596. public uint WorkerThreadCount
  597. {
  598. get
  599. {
  600. return Sdk.HP_Server_GetWorkerThreadCount(pServer);
  601. }
  602. set
  603. {
  604. Sdk.HP_Server_SetWorkerThreadCount(pServer, value);
  605. }
  606. }
  607. /// <summary>
  608. /// 读取或设置 Accept 预投递数量(根据负载调整设置,Accept 预投递数量越大则支持的并发连接请求越多)
  609. /// </summary>
  610. public uint AcceptSocketCount
  611. {
  612. get
  613. {
  614. return Sdk.HP_TcpServer_GetAcceptSocketCount(pServer);
  615. }
  616. set
  617. {
  618. Sdk.HP_TcpServer_SetAcceptSocketCount(pServer, value);
  619. }
  620. }
  621. /// <summary>
  622. /// 读取或设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为 1024 的倍数)
  623. /// </summary>
  624. public uint SocketBufferSize
  625. {
  626. get
  627. {
  628. return Sdk.HP_TcpServer_GetSocketBufferSize(pServer);
  629. }
  630. set
  631. {
  632. Sdk.HP_TcpServer_SetSocketBufferSize(pServer, value);
  633. }
  634. }
  635. /// <summary>
  636. /// 读取或设置监听 Socket 的等候队列大小(根据并发连接数量调整设置)
  637. /// </summary>
  638. public uint SocketListenQueue
  639. {
  640. get
  641. {
  642. return Sdk.HP_TcpServer_GetSocketListenQueue(pServer);
  643. }
  644. set
  645. {
  646. Sdk.HP_TcpServer_SetSocketListenQueue(pServer, value);
  647. }
  648. }
  649. /// <summary>
  650. /// 读取或设置 Socket 缓存对象锁定时间(毫秒,在锁定期间该 Socket 缓存对象不能被获取使用)
  651. /// </summary>
  652. public uint FreeSocketObjLockTime
  653. {
  654. get
  655. {
  656. return Sdk.HP_Server_GetFreeSocketObjLockTime(pServer);
  657. }
  658. set
  659. {
  660. Sdk.HP_Server_SetFreeSocketObjLockTime(pServer, value);
  661. }
  662. }
  663. /// <summary>
  664. /// 读取或设置 Socket 缓存池大小(通常设置为平均并发连接数量的 1/3 - 1/2)
  665. /// </summary>
  666. public uint FreeSocketObjPool
  667. {
  668. get
  669. {
  670. return Sdk.HP_Server_GetFreeSocketObjPool(pServer);
  671. }
  672. set
  673. {
  674. Sdk.HP_Server_SetFreeSocketObjPool(pServer, value);
  675. }
  676. }
  677. /// <summary>
  678. /// 读取或设置内存块缓存池大小(通常设置为 Socket 缓存池大小的 2 - 3 倍)
  679. /// </summary>
  680. public uint FreeBufferObjPool
  681. {
  682. get
  683. {
  684. return Sdk.HP_Server_GetFreeBufferObjPool(pServer);
  685. }
  686. set
  687. {
  688. Sdk.HP_Server_SetFreeBufferObjPool(pServer, value);
  689. }
  690. }
  691. /// <summary>
  692. /// 读取或设置内存块缓存池大小(通常设置为 Socket 缓存池大小的 2 - 3 倍)
  693. /// </summary>
  694. public uint FreeSocketObjHold
  695. {
  696. get
  697. {
  698. return Sdk.HP_Server_GetFreeSocketObjHold(pServer);
  699. }
  700. set
  701. {
  702. Sdk.HP_Server_SetFreeSocketObjHold(pServer, value);
  703. }
  704. }
  705. /// <summary>
  706. /// 读取或设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍)
  707. /// </summary>
  708. public uint FreeBufferObjHold
  709. {
  710. get
  711. {
  712. return Sdk.HP_Server_GetFreeBufferObjHold(pServer);
  713. }
  714. set
  715. {
  716. Sdk.HP_Server_SetFreeBufferObjHold(pServer, value);
  717. }
  718. }
  719. /// <summary>
  720. /// 读取或设置心跳包间隔(毫秒,0 则不发送心跳包)
  721. /// </summary>
  722. public uint KeepAliveTime
  723. {
  724. get
  725. {
  726. return Sdk.HP_TcpServer_GetKeepAliveTime(pServer);
  727. }
  728. set
  729. {
  730. Sdk.HP_TcpServer_SetKeepAliveTime(pServer, value);
  731. }
  732. }
  733. /// <summary>
  734. /// 读取或设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线)
  735. /// </summary>
  736. public uint KeepAliveInterval
  737. {
  738. get
  739. {
  740. return Sdk.HP_TcpServer_GetKeepAliveInterval(pServer);
  741. }
  742. set
  743. {
  744. Sdk.HP_TcpServer_SetKeepAliveInterval(pServer, value);
  745. }
  746. }
  747. /// <summary>
  748. /// 读取或设置是否标记静默时间(设置为 TRUE 时 DisconnectSilenceConnections() 和 GetSilencePeriod() 才有效,默认:FALSE)
  749. /// </summary>
  750. public bool MarkSilence
  751. {
  752. get
  753. {
  754. return Sdk.HP_Server_IsMarkSilence(pServer);
  755. }
  756. set
  757. {
  758. Sdk.HP_Server_SetMarkSilence(pServer, value);
  759. }
  760. }
  761. /// <summary>
  762. /// 获取或设置数据发送策略
  763. /// </summary>
  764. public SendPolicy SendPolicy
  765. {
  766. get
  767. {
  768. return Sdk.HP_Server_GetSendPolicy(pServer);
  769. }
  770. set
  771. {
  772. Sdk.HP_Server_SetSendPolicy(pServer, value);
  773. }
  774. }
  775. ///////////////////////////////////////////////////////////////////////////////////////
  776. /// <summary>
  777. /// 获取系统返回的错误码
  778. /// </summary>
  779. public int SYSGetLastError()
  780. {
  781. return Sdk.SYS_GetLastError();
  782. }
  783. /// <summary>
  784. /// 调用系统的 ::WSAGetLastError() 方法获取通信错误代码
  785. /// </summary>
  786. public int SYSWSAGetLastError()
  787. {
  788. return Sdk.SYS_WSAGetLastError();
  789. }
  790. /// <summary>
  791. /// 获取错误码
  792. /// </summary>
  793. public SocketError ErrorCode
  794. {
  795. get
  796. {
  797. return Sdk.HP_Server_GetLastError(pServer);
  798. }
  799. }
  800. /// <summary>
  801. /// 获取错误信息
  802. /// </summary>
  803. public string ErrorMessage
  804. {
  805. get
  806. {
  807. IntPtr ptr = Sdk.HP_Server_GetLastErrorDesc(pServer);
  808. string desc = Marshal.PtrToStringUni(ptr);
  809. return desc;
  810. }
  811. }
  812. ///////////////////////////////////////////////////////////////////////////////////////
  813. Sdk.OnPrepareListen _OnPrepareListen = null;
  814. Sdk.OnAccept _OnAccept = null;
  815. Sdk.OnReceive _OnReceive = null;
  816. Sdk.OnSend _OnSend = null;
  817. Sdk.OnClose _OnClose = null;
  818. Sdk.OnShutdown _OnShutdown = null;
  819. protected virtual void SetCallback()
  820. {
  821. _OnPrepareListen = new Sdk.OnPrepareListen(SDK_OnPrepareListen);
  822. _OnAccept = new Sdk.OnAccept(SDK_OnAccept);
  823. _OnSend = new Sdk.OnSend(SDK_OnSend);
  824. _OnReceive = new Sdk.OnReceive(SDK_OnReceive);
  825. _OnClose = new Sdk.OnClose(SDK_OnClose);
  826. _OnShutdown = new Sdk.OnShutdown(SDK_OnShutdown);
  827. Sdk.HP_Set_FN_Server_OnPrepareListen(pListener, _OnPrepareListen);
  828. Sdk.HP_Set_FN_Server_OnAccept(pListener, _OnAccept);
  829. Sdk.HP_Set_FN_Server_OnSend(pListener, _OnSend);
  830. Sdk.HP_Set_FN_Server_OnReceive(pListener, _OnReceive);
  831. Sdk.HP_Set_FN_Server_OnClose(pListener, _OnClose);
  832. Sdk.HP_Set_FN_Server_OnShutdown(pListener, _OnShutdown);
  833. }
  834. protected HandleResult SDK_OnPrepareListen(IntPtr soListen)
  835. {
  836. if (OnPrepareListen != null)
  837. {
  838. return OnPrepareListen(soListen);
  839. }
  840. return HandleResult.Ignore;
  841. }
  842. protected HandleResult SDK_OnAccept(IntPtr connId, IntPtr pClient)
  843. {
  844. if (OnAccept != null)
  845. {
  846. return OnAccept(connId, pClient);
  847. }
  848. return HandleResult.Ignore;
  849. }
  850. protected HandleResult SDK_OnSend(IntPtr connId, IntPtr pData, int length)
  851. {
  852. if (OnSend != null)
  853. {
  854. byte[] bytes = new byte[length];
  855. Marshal.Copy(pData, bytes, 0, length);
  856. return OnSend(connId, bytes);
  857. }
  858. return HandleResult.Ignore;
  859. }
  860. protected HandleResult SDK_OnReceive(IntPtr connId, IntPtr pData, int length)
  861. {
  862. if (OnPointerDataReceive != null)
  863. {
  864. return OnPointerDataReceive(connId, pData, length);
  865. }
  866. else if (OnReceive != null)
  867. {
  868. byte[] bytes = new byte[length];
  869. Marshal.Copy(pData, bytes, 0, length);
  870. return OnReceive(connId, bytes);
  871. }
  872. return HandleResult.Ignore;
  873. }
  874. protected HandleResult SDK_OnClose(IntPtr connId, SocketOperation enOperation, int errorCode)
  875. {
  876. if (OnClose != null)
  877. {
  878. return OnClose(connId, enOperation, errorCode);
  879. }
  880. return HandleResult.Ignore;
  881. }
  882. protected HandleResult SDK_OnShutdown()
  883. {
  884. if (OnShutdown != null)
  885. {
  886. return OnShutdown();
  887. }
  888. return HandleResult.Ignore;
  889. }
  890. /////////////////////////////////////////////////////////////////////////
  891. /// <summary>
  892. /// 根据错误码返回错误信息
  893. /// </summary>
  894. /// <param name="code"></param>
  895. /// <returns></returns>
  896. public string GetSocketErrorDesc(SocketError code)
  897. {
  898. IntPtr ptr = Sdk.HP_GetSocketErrorDesc(code);
  899. string desc = Marshal.PtrToStringUni(ptr);
  900. return desc;
  901. }
  902. /// <summary>
  903. /// 调用系统的 setsockopt()
  904. /// </summary>
  905. /// <param name="sock"></param>
  906. /// <param name="level"></param>
  907. /// <param name="name"></param>
  908. /// <param name="val"></param>
  909. /// <param name="len"></param>
  910. /// <returns></returns>
  911. ///
  912. public int SYS_SetSocketOption(IntPtr sock, int level, int name, IntPtr val, int len)
  913. {
  914. return Sdk.SYS_SetSocketOption(sock, level, name, val, len);
  915. }
  916. /// <summary>
  917. /// 调用系统的 getsockopt()
  918. /// </summary>
  919. /// <param name="sock"></param>
  920. /// <param name="level"></param>
  921. /// <param name="name"></param>
  922. /// <param name="val"></param>
  923. /// <param name="len"></param>
  924. /// <returns></returns>
  925. ///
  926. public int SYSGetSocketOption(IntPtr sock, int level, int name, IntPtr val, ref int len)
  927. {
  928. return Sdk.SYS_GetSocketOption(sock, level, name, val, ref len);
  929. }
  930. /// <summary>
  931. /// 调用系统的 ioctlsocket()
  932. /// </summary>
  933. /// <param name="sock"></param>
  934. /// <param name="cmd"></param>
  935. /// <param name="arg"></param>
  936. /// <returns></returns>
  937. ///
  938. public int SYSIoctlSocket(IntPtr sock, long cmd, IntPtr arg)
  939. {
  940. return Sdk.SYS_IoctlSocket(sock, cmd, arg);
  941. }
  942. /// <summary>
  943. /// 调用系统的 ::WSAIoctl()
  944. /// </summary>
  945. /// <param name="sock"></param>
  946. /// <param name="dwIoControlCode"></param>
  947. /// <param name="lpvInBuffer"></param>
  948. /// <param name="cbInBuffer"></param>
  949. /// <param name="lpvOutBuffer"></param>
  950. /// <param name="cbOutBuffer"></param>
  951. /// <param name="lpcbBytesReturned"></param>
  952. /// <returns></returns>
  953. public int SYS_WSAIoctl(IntPtr sock, uint dwIoControlCode, IntPtr lpvInBuffer, uint cbInBuffer,
  954. IntPtr lpvOutBuffer, uint cbOutBuffer, uint lpcbBytesReturned)
  955. {
  956. return Sdk.SYS_WSAIoctl(sock, dwIoControlCode, lpvInBuffer, cbInBuffer,
  957. lpvOutBuffer, cbOutBuffer, lpcbBytesReturned);
  958. }
  959. /// <summary>
  960. /// 由结构体转换为byte数组
  961. /// </summary>
  962. public byte[] StructureToByte<T>(T structure)
  963. {
  964. int size = Marshal.SizeOf(typeof(T));
  965. byte[] buffer = new byte[size];
  966. IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
  967. try
  968. {
  969. Marshal.StructureToPtr(structure, bufferIntPtr, true);
  970. Marshal.Copy(bufferIntPtr, buffer, 0, size);
  971. }
  972. finally
  973. {
  974. Marshal.FreeHGlobal(bufferIntPtr);
  975. }
  976. return buffer;
  977. }
  978. /// <summary>
  979. /// 由byte数组转换为结构体
  980. /// </summary>
  981. public T ByteToStructure<T>(byte[] dataBuffer)
  982. {
  983. object structure = null;
  984. int size = Marshal.SizeOf(typeof(T));
  985. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  986. try
  987. {
  988. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  989. structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
  990. }
  991. finally
  992. {
  993. Marshal.FreeHGlobal(allocIntPtr);
  994. }
  995. return (T)structure;
  996. }
  997. /// <summary>
  998. /// 对象序列化成byte[]
  999. /// </summary>
  1000. /// <param name="obj"></param>
  1001. /// <returns></returns>
  1002. public byte[] ObjectToBytes(object obj)
  1003. {
  1004. using (MemoryStream ms = new MemoryStream())
  1005. {
  1006. IFormatter formatter = new BinaryFormatter();
  1007. formatter.Serialize(ms, obj);
  1008. return ms.GetBuffer();
  1009. }
  1010. }
  1011. /// <summary>
  1012. /// byte[]序列化成对象
  1013. /// </summary>
  1014. /// <param name="Bytes"></param>
  1015. /// <returns></returns>
  1016. public object BytesToObject(byte[] bytes)
  1017. {
  1018. using (MemoryStream ms = new MemoryStream(bytes))
  1019. {
  1020. IFormatter formatter = new BinaryFormatter();
  1021. return formatter.Deserialize(ms);
  1022. }
  1023. }
  1024. /// <summary>
  1025. /// byte[]转结构体
  1026. /// </summary>
  1027. /// <typeparam name="T"></typeparam>
  1028. /// <param name="bytes"></param>
  1029. /// <returns></returns>
  1030. public T BytesToStruct<T>(byte[] bytes)
  1031. {
  1032. Type strcutType = typeof(T);
  1033. int size = Marshal.SizeOf(strcutType);
  1034. IntPtr buffer = Marshal.AllocHGlobal(size);
  1035. try
  1036. {
  1037. Marshal.Copy(bytes, 0, buffer, size);
  1038. return (T)Marshal.PtrToStructure(buffer, strcutType);
  1039. }
  1040. finally
  1041. {
  1042. Marshal.FreeHGlobal(buffer);
  1043. }
  1044. }
  1045. }
  1046. }