TcpClient.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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;
  8. using System.Runtime.Serialization.Formatters.Binary;
  9. namespace HPSocketCS
  10. {
  11. public class TcpClientEvent
  12. {
  13. public delegate HandleResult OnPrepareConnectEventHandler(TcpClient sender, uint socket);
  14. public delegate HandleResult OnConnectEventHandler(TcpClient sender);
  15. public delegate HandleResult OnSendEventHandler(TcpClient sender, byte[] bytes);
  16. public delegate HandleResult OnReceiveEventHandler(TcpClient sender, byte[] bytes);
  17. public delegate HandleResult OnPointerDataReceiveEventHandler(TcpClient sender, IntPtr pData, int length);
  18. public delegate HandleResult OnCloseEventHandler(TcpClient sender, SocketOperation enOperation, int errorCode);
  19. }
  20. public class TcpClient
  21. {
  22. protected IntPtr _pClient = IntPtr.Zero;
  23. protected IntPtr pClient
  24. {
  25. get
  26. {
  27. return _pClient;
  28. }
  29. set
  30. {
  31. _pClient = value;
  32. }
  33. }
  34. protected IntPtr pListener = IntPtr.Zero;
  35. protected bool IsCreate = false;
  36. ConnectionExtra ExtraData = new ConnectionExtra();
  37. /****************************************************/
  38. /// <summary>
  39. /// 准备连接了事件
  40. /// </summary>
  41. public event TcpClientEvent.OnPrepareConnectEventHandler OnPrepareConnect;
  42. /// <summary>
  43. /// 连接事件
  44. /// </summary>
  45. public event TcpClientEvent.OnConnectEventHandler OnConnect;
  46. /// <summary>
  47. /// 数据发送事件
  48. /// </summary>
  49. public event TcpClientEvent.OnSendEventHandler OnSend;
  50. /// <summary>
  51. /// 数据到达事件
  52. /// </summary>
  53. public event TcpClientEvent.OnReceiveEventHandler OnReceive;
  54. /// <summary>
  55. /// 数据到达事件(指针数据)
  56. /// </summary>
  57. public event TcpClientEvent.OnPointerDataReceiveEventHandler OnPointerDataReceive;
  58. /// <summary>
  59. /// 连接关闭事件
  60. /// </summary>
  61. public event TcpClientEvent.OnCloseEventHandler OnClose;
  62. public TcpClient()
  63. {
  64. CreateListener();
  65. }
  66. ~TcpClient()
  67. {
  68. Destroy();
  69. }
  70. /// <summary>
  71. /// 创建socket监听&服务组件
  72. /// </summary>
  73. /// <returns></returns>
  74. protected virtual bool CreateListener()
  75. {
  76. if (IsCreate == true || pListener != IntPtr.Zero || pClient != IntPtr.Zero)
  77. {
  78. return false;
  79. }
  80. pListener = Sdk.Create_HP_TcpClientListener();
  81. if (pListener == IntPtr.Zero)
  82. {
  83. return false;
  84. }
  85. pClient = Sdk.Create_HP_TcpClient(pListener);
  86. if (pClient == IntPtr.Zero)
  87. {
  88. return false;
  89. }
  90. IsCreate = true;
  91. return true;
  92. }
  93. /// <summary>
  94. /// 终止服务并释放资源
  95. /// </summary>
  96. public virtual void Destroy()
  97. {
  98. Stop();
  99. if (pClient != IntPtr.Zero)
  100. {
  101. Sdk.Destroy_HP_TcpClient(pClient);
  102. pClient = IntPtr.Zero;
  103. }
  104. if (pListener != IntPtr.Zero)
  105. {
  106. Sdk.Destroy_HP_TcpClientListener(pListener);
  107. pListener = IntPtr.Zero;
  108. }
  109. IsCreate = false;
  110. }
  111. /// <summary>
  112. /// 启动通讯组件并连接到服务器
  113. /// </summary>
  114. /// <param name="address">远程地址</param>
  115. /// <param name="port">远程端口</param>
  116. /// <param name="async">是否异步</param>
  117. /// <returns></returns>
  118. public bool Connect(string address, ushort port, bool async = true)
  119. {
  120. if (string.IsNullOrEmpty(address) == true)
  121. {
  122. throw new Exception("address is null");
  123. }
  124. else if (port == 0)
  125. {
  126. throw new Exception("port is zero");
  127. }
  128. if (IsStarted == true)
  129. {
  130. return false;
  131. }
  132. this.SetCallback();
  133. return Sdk.HP_Client_Start(pClient, address, port, async);
  134. }
  135. /// <summary>
  136. /// 启动通讯组件并连接到服务器
  137. /// </summary>
  138. /// <param name="address">远程地址</param>
  139. /// <param name="port">远程端口</param>
  140. /// <param name="bindAddress">本地绑定到哪个ip?,多ip下可以选择绑定到指定ip</param>
  141. /// <param name="async">是否异步</param>
  142. /// <returns></returns>
  143. public bool Connect(string address, ushort port, string bindAddress, bool async = true)
  144. {
  145. if (string.IsNullOrEmpty(address) == true)
  146. {
  147. throw new Exception("address is null");
  148. }
  149. else if (port == 0)
  150. {
  151. throw new Exception("port is zero");
  152. }
  153. if (IsStarted == true)
  154. {
  155. return false;
  156. }
  157. this.SetCallback();
  158. return Sdk.HP_Client_StartWithBindAddress(pClient, address, port, async, bindAddress);
  159. }
  160. /// <summary>
  161. /// 停止通讯组件
  162. /// </summary>
  163. /// <returns></returns>
  164. public bool Stop()
  165. {
  166. if (IsStarted == false)
  167. {
  168. return false;
  169. }
  170. return Sdk.HP_Client_Stop(pClient);
  171. }
  172. /// <summary>
  173. /// 发送数据
  174. /// </summary>
  175. /// <param name="connId"></param>
  176. /// <param name="bytes"></param>
  177. /// <param name="size"></param>
  178. /// <returns></returns>
  179. public bool Send(byte[] bytes, int size)
  180. {
  181. return Sdk.HP_Client_Send(pClient, bytes, size);
  182. }
  183. /// <summary>
  184. /// 发送数据
  185. /// </summary>
  186. /// <param name="connId"></param>
  187. /// <param name="bufferPtr"></param>
  188. /// <param name="size"></param>
  189. /// <returns></returns>
  190. public bool Send(IntPtr bufferPtr, int size)
  191. {
  192. return Sdk.HP_Client_Send(pClient, bufferPtr, size);
  193. }
  194. /// <summary>
  195. /// 发送数据
  196. /// </summary>
  197. /// <param name="connId"></param>
  198. /// <param name="bufferPtr"></param>
  199. /// <param name="size"></param>
  200. /// <returns></returns>
  201. public bool Send<T>(T obj)
  202. {
  203. byte[] buffer = StructureToByte<T>(obj);
  204. return Send(buffer, buffer.Length);
  205. }
  206. /// <summary>
  207. /// 序列化对象后发送数据,序列化对象所属类必须标记[Serializable]
  208. /// </summary>
  209. /// <param name="connId"></param>
  210. /// <param name="bufferPtr"></param>
  211. /// <param name="size"></param>
  212. /// <returns></returns>
  213. public bool SendBySerializable(object obj)
  214. {
  215. byte[] buffer = ObjectToBytes(obj);
  216. return Send(buffer, buffer.Length);
  217. }
  218. /// <summary>
  219. /// 发送数据
  220. /// </summary>
  221. /// <param name="connId"></param>
  222. /// <param name="bytes"></param>
  223. /// <param name="offset">针对bytes的偏移</param>
  224. /// <param name="size">发多大</param>
  225. /// <returns></returns>
  226. public bool Send(byte[] bytes, int offset, int size)
  227. {
  228. return Sdk.HP_Client_SendPart(pClient, bytes, size, offset);
  229. }
  230. /// <summary>
  231. /// 发送数据
  232. /// </summary>
  233. /// <param name="connId"></param>
  234. /// <param name="bufferPtr"></param>
  235. /// <param name="offset">针对bufferPtr的偏移</param>
  236. /// <param name="size">发多大</param>
  237. /// <returns></returns>
  238. public bool Send(IntPtr bufferPtr, int offset, int size)
  239. {
  240. return Sdk.HP_Client_SendPart(pClient, bufferPtr, size, offset);
  241. }
  242. /// <summary>
  243. /// 发送多组数据
  244. /// 向指定连接发送多组数据
  245. /// TCP - 顺序发送所有数据包
  246. /// </summary>
  247. /// <param name="connId">连接 ID</param>
  248. /// <param name="pBuffers">发送缓冲区数组</param>
  249. /// <param name="iCount">发送缓冲区数目</param>
  250. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  251. public bool SendPackets(WSABUF[] buffers, int count)
  252. {
  253. return Sdk.HP_Client_SendPackets(pClient, buffers, count);
  254. }
  255. /// <summary>
  256. /// 发送多组数据
  257. /// 向指定连接发送多组数据
  258. /// TCP - 顺序发送所有数据包
  259. /// </summary>
  260. /// <param name="connId">连接 ID</param>
  261. /// <param name="pBuffers">发送缓冲区数组</param>
  262. /// <param name="iCount">发送缓冲区数目</param>
  263. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  264. public bool SendPackets<T>(T[] objects)
  265. {
  266. bool ret = false;
  267. WSABUF[] buffer = new WSABUF[objects.Length];
  268. IntPtr[] ptrs = new IntPtr[buffer.Length];
  269. try
  270. {
  271. for (int i = 0; i < objects.Length; i++)
  272. {
  273. buffer[i].Length = Marshal.SizeOf(typeof(T));
  274. ptrs[i] = Marshal.AllocHGlobal(buffer[i].Length);
  275. Marshal.StructureToPtr(objects[i], ptrs[i], true);
  276. buffer[i].Buffer = ptrs[i];
  277. }
  278. ret = SendPackets(buffer, buffer.Length);
  279. }
  280. catch (Exception ex)
  281. {
  282. throw ex;
  283. }
  284. finally
  285. {
  286. for (int i = 0; i < ptrs.Length; i++)
  287. {
  288. if (ptrs[i] != IntPtr.Zero)
  289. {
  290. Marshal.FreeHGlobal(ptrs[i]);
  291. }
  292. }
  293. }
  294. return ret;
  295. }
  296. /// <summary>
  297. /// 名称:发送小文件
  298. /// 描述:向指定连接发送 4096 KB 以下的小文件
  299. /// </summary>
  300. /// <param name="filePath">文件路径</param>
  301. /// <param name="head">头部附加数据</param>
  302. /// <param name="tail">尾部附加数据</param>
  303. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  304. public bool SendSmallFile(string filePath, ref WSABUF head, ref WSABUF tail)
  305. {
  306. return Sdk.HP_TcpClient_SendSmallFile(pClient, filePath, ref head, ref tail);
  307. }
  308. /// <summary>
  309. /// 名称:发送小文件
  310. /// 描述:向指定连接发送 4096 KB 以下的小文件
  311. /// </summary>
  312. /// <param name="filePath">文件路径</param>
  313. /// <param name="head">头部附加数据,可以为null</param>
  314. /// <param name="tail">尾部附加数据,可以为null</param>
  315. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  316. public bool SendSmallFile(string filePath, byte[] head, byte[] tail)
  317. {
  318. IntPtr pHead = IntPtr.Zero;
  319. IntPtr pTail = IntPtr.Zero;
  320. WSABUF wsaHead = new WSABUF() { Length = 0, Buffer = pHead };
  321. WSABUF wsatail = new WSABUF() { Length = 0, Buffer = pTail };
  322. if (head != null)
  323. {
  324. wsaHead.Length = head.Length;
  325. wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(head, 0);
  326. }
  327. if (tail != null)
  328. {
  329. wsaHead.Length = tail.Length;
  330. wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(tail, 0);
  331. }
  332. return SendSmallFile(filePath, ref wsaHead, ref wsatail);
  333. }
  334. /// <summary>
  335. /// 名称:发送小文件
  336. /// 描述:向指定连接发送 4096 KB 以下的小文件
  337. /// </summary>
  338. /// <param name="filePath">文件路径</param>
  339. /// <param name="head">头部附加数据,可以为null</param>
  340. /// <param name="tail">尾部附加数据,可以为null</param>
  341. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  342. public bool SendSmallFile<T1, T2>(string filePath, T1 head, T2 tail)
  343. {
  344. byte[] headBuffer = null;
  345. if (head != null)
  346. {
  347. headBuffer = StructureToByte<T1>(head);
  348. }
  349. byte[] tailBuffer = null;
  350. if (tail != null)
  351. {
  352. tailBuffer = StructureToByte<T2>(tail);
  353. }
  354. return SendSmallFile(filePath, headBuffer, tailBuffer);
  355. }
  356. /// <summary>
  357. /// 获取错误码
  358. /// </summary>
  359. public SocketError ErrorCode
  360. {
  361. get
  362. {
  363. return Sdk.HP_Client_GetLastError(pClient);
  364. }
  365. }
  366. /// <summary>
  367. /// 获取错误信息
  368. /// </summary>
  369. public string ErrorMessage
  370. {
  371. get
  372. {
  373. IntPtr ptr = Sdk.HP_Client_GetLastErrorDesc(pClient);
  374. string desc = Marshal.PtrToStringUni(ptr);
  375. return desc;
  376. }
  377. }
  378. /// <summary>
  379. /// </summary>
  380. /// <param name="connId"></param>
  381. /// <param name="length"></param>
  382. /// <returns></returns>
  383. public bool GetPendingDataLength(ref int length)
  384. {
  385. return Sdk.HP_Client_GetPendingDataLength(pClient, ref length);
  386. }
  387. /// <summary>
  388. /// 获取附加数据
  389. /// </summary>
  390. /// <returns></returns>
  391. public T GetExtra<T>()
  392. {
  393. IntPtr key = (IntPtr)this.GetHashCode();
  394. return (T)ExtraData.GetExtra(key);
  395. }
  396. /// <summary>
  397. /// 设置附加数据
  398. ///
  399. /// </summary>
  400. /// <param name="value"></param>
  401. /// <returns></returns>
  402. public bool SetExtra(object newValue)
  403. {
  404. IntPtr key = (IntPtr)this.GetHashCode();
  405. return ExtraData.SetExtra(key, newValue);
  406. }
  407. /// <summary>
  408. /// 删除附加数据
  409. /// </summary>
  410. /// <param name="key"></param>
  411. /// <returns></returns>
  412. public bool RemoveExtra()
  413. {
  414. IntPtr key = (IntPtr)this.GetHashCode();
  415. return ExtraData.RemoveExtra(key);
  416. }
  417. ///// <summary>
  418. ///// 设置连接的附加数据
  419. ///// </summary>
  420. ///// <param name="connId"></param>
  421. ///// <param name="obj">如果为null,则为释放设置的数据</param>
  422. ///// <returns></returns>
  423. //public void SetExtra(object obj)
  424. //{
  425. // // 释放附加数据
  426. // IntPtr ptr = Sdk.HP_Client_GetExtra(pClient);
  427. // if (ptr != IntPtr.Zero)
  428. // {
  429. // Marshal.FreeHGlobal(ptr);
  430. // ptr = IntPtr.Zero;
  431. // }
  432. // if (obj != null)
  433. // {
  434. // // 设置附加数据
  435. // ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));
  436. // Marshal.StructureToPtr(obj, ptr, false);
  437. // }
  438. // Sdk.HP_Client_SetExtra(pClient, ptr);
  439. //}
  440. ///// <summary>
  441. ///// 获取附加数据
  442. ///// 如设置的是个结构体/类对象,可以用 Type objA = (Type)Marshal.PtrToStructure(ptr, typeof(Type)) 获取
  443. ///// 其中Type是结构体/类名,ptr是该方法的传出值,在该方法返回为true的时候可用
  444. ///// </summary>
  445. ///// <param name="connId"></param>
  446. ///// <param name="ptr"></param>
  447. ///// <returns></returns>
  448. //public T GetExtra<T>()
  449. //{
  450. // IntPtr ptr = Sdk.HP_Client_GetExtra(pClient);
  451. // T obj = default(T);
  452. // if (ptr != IntPtr.Zero)
  453. // {
  454. // obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
  455. // }
  456. // return obj;
  457. //}
  458. ///// <summary>
  459. ///// 移除连接中的附加数据, 同SetExtra(null)
  460. ///// </summary>
  461. ///// <param name="connId"></param>
  462. ///// <returns></returns>
  463. //public void RemoveExtra()
  464. //{
  465. // SetExtra(null);
  466. //}
  467. ///// <summary>
  468. ///// 获取或这是附加数据
  469. ///// 推荐使用泛型方法:T GetExtra<T>()
  470. ///// </summary>
  471. //public object Extra
  472. //{
  473. // get
  474. // {
  475. // return GetExtra<object>();
  476. // }
  477. // set
  478. // {
  479. // SetExtra(value);
  480. // }
  481. //}
  482. /// <summary>
  483. /// 获取监听socket的地址信息
  484. /// </summary>
  485. /// <param name="ip"></param>
  486. /// <param name="ipLength"></param>
  487. /// <param name="port"></param>
  488. /// <returns></returns>
  489. public bool GetListenAddress(ref string ip, ref ushort port)
  490. {
  491. int ipLength = 40;
  492. StringBuilder sb = new StringBuilder(ipLength);
  493. bool ret = Sdk.HP_Client_GetLocalAddress(pClient, sb, ref ipLength, ref port);
  494. if (ret == true)
  495. {
  496. ip = sb.ToString();
  497. }
  498. return ret;
  499. }
  500. /// <summary>
  501. /// 是否启动
  502. /// </summary>
  503. public bool IsStarted
  504. {
  505. get
  506. {
  507. if (pClient == IntPtr.Zero)
  508. {
  509. return false;
  510. }
  511. return Sdk.HP_Client_HasStarted(pClient);
  512. }
  513. }
  514. /// <summary>
  515. /// 状态
  516. /// </summary>
  517. public ServiceState State
  518. {
  519. get
  520. {
  521. return Sdk.HP_Client_GetState(pClient);
  522. }
  523. }
  524. /// <summary>
  525. /// 获取该组件对象的连接Id
  526. /// </summary>
  527. public IntPtr ConnectionId
  528. {
  529. get
  530. {
  531. return Sdk.HP_Client_GetConnectionID(pClient);
  532. }
  533. }
  534. ///////////////////////////////////////////////////////////////////////////////////////
  535. /// <summary>
  536. /// 读取或设置内存块缓存池大小(通常设置为 -> PUSH 模型:5 - 10;PULL 模型:10 - 20 )
  537. /// </summary>
  538. public uint FreeBufferPoolSize
  539. {
  540. get
  541. {
  542. return Sdk.HP_Client_GetFreeBufferPoolSize(pClient);
  543. }
  544. set
  545. {
  546. Sdk.HP_Client_SetFreeBufferPoolSize(pClient, value);
  547. }
  548. }
  549. /// <summary>
  550. /// 读取或设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍)
  551. /// </summary>
  552. public uint FreeBufferPoolHold
  553. {
  554. get
  555. {
  556. return Sdk.HP_Client_GetFreeBufferPoolHold(pClient);
  557. }
  558. set
  559. {
  560. Sdk.HP_Client_SetFreeBufferPoolHold(pClient, value);
  561. }
  562. }
  563. ///////////////////////////////////////////////////////////////////////////////////////
  564. /// <summary>
  565. /// 读取或设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为:(N * 1024) - sizeof(TBufferObj))
  566. /// </summary>
  567. public uint SocketBufferSize
  568. {
  569. get
  570. {
  571. return Sdk.HP_TcpClient_GetSocketBufferSize(pClient);
  572. }
  573. set
  574. {
  575. Sdk.HP_TcpClient_SetSocketBufferSize(pClient, value);
  576. }
  577. }
  578. /// <summary>
  579. /// 读取或设置心跳包间隔(毫秒,0 则不发送心跳包)
  580. /// </summary>
  581. public uint KeepAliveTime
  582. {
  583. get
  584. {
  585. return Sdk.HP_TcpClient_GetKeepAliveTime(pClient);
  586. }
  587. set
  588. {
  589. Sdk.HP_TcpClient_SetKeepAliveTime(pClient, value);
  590. }
  591. }
  592. /// <summary>
  593. /// 读取或设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线)
  594. /// </summary>
  595. public uint KeepAliveInterval
  596. {
  597. get
  598. {
  599. return Sdk.HP_TcpClient_GetKeepAliveInterval(pClient);
  600. }
  601. set
  602. {
  603. Sdk.HP_TcpClient_SetKeepAliveInterval(pClient, value);
  604. }
  605. }
  606. /// <summary>
  607. /// 根据错误码返回错误信息
  608. /// </summary>
  609. /// <param name="code"></param>
  610. /// <returns></returns>
  611. public string GetSocketErrorDesc(SocketError code)
  612. {
  613. IntPtr ptr = Sdk.HP_GetSocketErrorDesc(code);
  614. string desc = Marshal.PtrToStringUni(ptr);
  615. return desc;
  616. }
  617. ///////////////////////////////////////////////////////////////////////////////////////
  618. Sdk.OnPrepareConnect _OnPrepareConnect = null;
  619. Sdk.OnConnect _OnConnect = null;
  620. Sdk.OnReceive _OnReceive = null;
  621. Sdk.OnSend _OnSend = null;
  622. Sdk.OnClose _OnClose = null;
  623. /// <summary>
  624. /// 设置回调函数
  625. /// </summary>
  626. protected virtual void SetCallback()
  627. {
  628. // 设置 Socket 监听器回调函数
  629. _OnPrepareConnect = new Sdk.OnPrepareConnect(SDK_OnPrepareConnect);
  630. _OnConnect = new Sdk.OnConnect(SDK_OnConnect);
  631. _OnSend = new Sdk.OnSend(SDK_OnSend);
  632. _OnReceive = new Sdk.OnReceive(SDK_OnReceive);
  633. _OnClose = new Sdk.OnClose(SDK_OnClose);
  634. Sdk.HP_Set_FN_Client_OnPrepareConnect(pListener, _OnPrepareConnect);
  635. Sdk.HP_Set_FN_Client_OnConnect(pListener, _OnConnect);
  636. Sdk.HP_Set_FN_Client_OnSend(pListener, _OnSend);
  637. Sdk.HP_Set_FN_Client_OnReceive(pListener, _OnReceive);
  638. Sdk.HP_Set_FN_Client_OnClose(pListener, _OnClose);
  639. }
  640. protected HandleResult SDK_OnPrepareConnect(IntPtr pClient, uint socket)
  641. {
  642. if (OnPrepareConnect != null)
  643. {
  644. return OnPrepareConnect(this, socket);
  645. }
  646. return HandleResult.Ignore;
  647. }
  648. protected HandleResult SDK_OnConnect(IntPtr pClient)
  649. {
  650. if (OnConnect != null)
  651. {
  652. return OnConnect(this);
  653. }
  654. return HandleResult.Ignore;
  655. }
  656. protected HandleResult SDK_OnSend(IntPtr pClient, IntPtr pData, int length)
  657. {
  658. if (OnSend != null)
  659. {
  660. byte[] bytes = new byte[length];
  661. Marshal.Copy(pData, bytes, 0, length);
  662. return OnSend(this, bytes);
  663. }
  664. return HandleResult.Ignore;
  665. }
  666. protected HandleResult SDK_OnReceive(IntPtr pClient, IntPtr pData, int length)
  667. {
  668. if (OnPointerDataReceive != null)
  669. {
  670. return OnPointerDataReceive(this, pData, length);
  671. }
  672. else if (OnReceive != null)
  673. {
  674. byte[] bytes = new byte[length];
  675. Marshal.Copy(pData, bytes, 0, length);
  676. return OnReceive(this, bytes);
  677. }
  678. return HandleResult.Ignore;
  679. }
  680. protected HandleResult SDK_OnClose(IntPtr pClient, SocketOperation enOperation, int errorCode)
  681. {
  682. if (OnClose != null)
  683. {
  684. return OnClose(this, enOperation, errorCode);
  685. }
  686. return HandleResult.Ignore;
  687. }
  688. ///////////////////////////////////////////////////////////////////////////
  689. /// <summary>
  690. /// 获取系统返回的错误码
  691. /// </summary>
  692. public int SYSGetLastError()
  693. {
  694. return Sdk.SYS_GetLastError();
  695. }
  696. /// <summary>
  697. /// 调用系统的 ::WSAGetLastError() 方法获取通信错误代码
  698. /// </summary>
  699. public int SYSWSAGetLastError()
  700. {
  701. return Sdk.SYS_WSAGetLastError();
  702. }
  703. /// <summary>
  704. /// 调用系统的 setsockopt()
  705. /// </summary>
  706. /// <param name="sock"></param>
  707. /// <param name="level"></param>
  708. /// <param name="name"></param>
  709. /// <param name="val"></param>
  710. /// <param name="len"></param>
  711. /// <returns></returns>
  712. ///
  713. public int SYS_SetSocketOption(IntPtr sock, int level, int name, IntPtr val, int len)
  714. {
  715. return Sdk.SYS_SetSocketOption(sock, level, name, val, len);
  716. }
  717. /// <summary>
  718. /// 调用系统的 getsockopt()
  719. /// </summary>
  720. /// <param name="sock"></param>
  721. /// <param name="level"></param>
  722. /// <param name="name"></param>
  723. /// <param name="val"></param>
  724. /// <param name="len"></param>
  725. /// <returns></returns>
  726. ///
  727. public int SYSGetSocketOption(IntPtr sock, int level, int name, IntPtr val, ref int len)
  728. {
  729. return Sdk.SYS_GetSocketOption(sock, level, name, val, ref len);
  730. }
  731. /// <summary>
  732. /// 调用系统的 ioctlsocket()
  733. /// </summary>
  734. /// <param name="sock"></param>
  735. /// <param name="cmd"></param>
  736. /// <param name="arg"></param>
  737. /// <returns></returns>
  738. ///
  739. public int SYSIoctlSocket(IntPtr sock, long cmd, IntPtr arg)
  740. {
  741. return Sdk.SYS_IoctlSocket(sock, cmd, arg);
  742. }
  743. /// <summary>
  744. /// 调用系统的 ::WSAIoctl()
  745. /// </summary>
  746. /// <param name="sock"></param>
  747. /// <param name="dwIoControlCode"></param>
  748. /// <param name="lpvInBuffer"></param>
  749. /// <param name="cbInBuffer"></param>
  750. /// <param name="lpvOutBuffer"></param>
  751. /// <param name="cbOutBuffer"></param>
  752. /// <param name="lpcbBytesReturned"></param>
  753. /// <returns></returns>
  754. public int SYS_WSAIoctl(IntPtr sock, uint dwIoControlCode, IntPtr lpvInBuffer, uint cbInBuffer,
  755. IntPtr lpvOutBuffer, uint cbOutBuffer, uint lpcbBytesReturned)
  756. {
  757. return Sdk.SYS_WSAIoctl(sock, dwIoControlCode, lpvInBuffer, cbInBuffer,
  758. lpvOutBuffer, cbOutBuffer, lpcbBytesReturned);
  759. }
  760. /// <summary>
  761. /// 由结构体转换为byte数组
  762. /// </summary>
  763. public byte[] StructureToByte<T>(T structure)
  764. {
  765. int size = Marshal.SizeOf(typeof(T));
  766. byte[] buffer = new byte[size];
  767. IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
  768. try
  769. {
  770. Marshal.StructureToPtr(structure, bufferIntPtr, true);
  771. Marshal.Copy(bufferIntPtr, buffer, 0, size);
  772. }
  773. finally
  774. {
  775. Marshal.FreeHGlobal(bufferIntPtr);
  776. }
  777. return buffer;
  778. }
  779. /// <summary>
  780. /// 由byte数组转换为结构体
  781. /// </summary>
  782. public T ByteToStructure<T>(byte[] dataBuffer)
  783. {
  784. object structure = null;
  785. int size = Marshal.SizeOf(typeof(T));
  786. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  787. try
  788. {
  789. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  790. structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
  791. }
  792. finally
  793. {
  794. Marshal.FreeHGlobal(allocIntPtr);
  795. }
  796. return (T)structure;
  797. }
  798. /// <summary>
  799. /// 对象序列化成byte[]
  800. /// </summary>
  801. /// <param name="obj"></param>
  802. /// <returns></returns>
  803. public byte[] ObjectToBytes(object obj)
  804. {
  805. using (MemoryStream ms = new MemoryStream())
  806. {
  807. IFormatter formatter = new BinaryFormatter();
  808. formatter.Serialize(ms, obj);
  809. return ms.GetBuffer();
  810. }
  811. }
  812. /// <summary>
  813. /// byte[]序列化成对象
  814. /// </summary>
  815. /// <param name="Bytes"></param>
  816. /// <returns></returns>
  817. public object BytesToObject(byte[] bytes)
  818. {
  819. using (MemoryStream ms = new MemoryStream(bytes))
  820. {
  821. IFormatter formatter = new BinaryFormatter();
  822. return formatter.Deserialize(ms);
  823. }
  824. }
  825. /// <summary>
  826. /// byte[]转结构体
  827. /// </summary>
  828. /// <typeparam name="T"></typeparam>
  829. /// <param name="bytes"></param>
  830. /// <returns></returns>
  831. public T BytesToStruct<T>(byte[] bytes)
  832. {
  833. Type strcutType = typeof(T);
  834. int size = Marshal.SizeOf(strcutType);
  835. IntPtr buffer = Marshal.AllocHGlobal(size);
  836. try
  837. {
  838. Marshal.Copy(bytes, 0, buffer, size);
  839. return (T)Marshal.PtrToStructure(buffer, strcutType);
  840. }
  841. finally
  842. {
  843. Marshal.FreeHGlobal(buffer);
  844. }
  845. }
  846. }
  847. }