TcpServer.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  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. using HPSocketCS.Extended;
  10. namespace HPSocketCS
  11. {
  12. public class TcpServerEvent
  13. {
  14. public delegate HandleResult OnSendEventHandler(IntPtr connId, byte[] bytes);
  15. public delegate HandleResult OnReceiveEventHandler(IntPtr connId, byte[] bytes);
  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
  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.OnCloseEventHandler OnClose;
  64. /// <summary>
  65. /// 服务器关闭事件
  66. /// </summary>
  67. public event TcpServerEvent.OnShutdownEventHandler OnShutdown;
  68. protected bool IsCreate = false;
  69. /// <summary>
  70. /// tcpserver构造
  71. /// </summary>
  72. public TcpServer()
  73. {
  74. CreateListener();
  75. }
  76. ~TcpServer()
  77. {
  78. Destroy();
  79. }
  80. /// <summary>
  81. /// 创建socket监听&服务组件
  82. /// </summary>
  83. /// <param name="isUseDefaultCallback">是否使用tcpserver类默认回调函数</param>
  84. /// <returns></returns>
  85. protected virtual bool CreateListener()
  86. {
  87. if (IsCreate == true || pListener != IntPtr.Zero || pServer != IntPtr.Zero)
  88. {
  89. return false;
  90. }
  91. pListener = Sdk.Create_HP_TcpServerListener();
  92. if (pListener == IntPtr.Zero)
  93. {
  94. return false;
  95. }
  96. pServer = Sdk.Create_HP_TcpServer(pListener);
  97. if (pServer == IntPtr.Zero)
  98. {
  99. return false;
  100. }
  101. IsCreate = true;
  102. return true;
  103. }
  104. /// <summary>
  105. /// 终止服务并释放资源
  106. /// </summary>
  107. public virtual void Destroy()
  108. {
  109. Stop();
  110. if (pServer != IntPtr.Zero)
  111. {
  112. Sdk.Destroy_HP_TcpServer(pServer);
  113. pServer = IntPtr.Zero;
  114. }
  115. if (pListener != IntPtr.Zero)
  116. {
  117. Sdk.Destroy_HP_TcpServerListener(pListener);
  118. pListener = IntPtr.Zero;
  119. }
  120. IsCreate = false;
  121. }
  122. /// <summary>
  123. /// 启动服务
  124. /// </summary>
  125. /// <param name="address"></param>
  126. /// <param name="port"></param>
  127. /// <returns></returns>
  128. public bool Start()
  129. {
  130. if (IsCreate == false)
  131. {
  132. return false;
  133. }
  134. if (IsStarted == true)
  135. {
  136. return false;
  137. }
  138. SetCallback();
  139. return Sdk.HP_Server_Start(pServer, IpAddress, Port);
  140. }
  141. /// <summary>
  142. /// 停止服务
  143. /// </summary>
  144. /// <returns></returns>
  145. public bool Stop()
  146. {
  147. if (IsStarted == false)
  148. {
  149. return false;
  150. }
  151. return Sdk.HP_Server_Stop(pServer);
  152. }
  153. /// <summary>
  154. /// 发送数据
  155. /// </summary>
  156. /// <param name="connId"></param>
  157. /// <param name="bytes"></param>
  158. /// <param name="size"></param>
  159. /// <returns></returns>
  160. public bool Send(IntPtr connId, byte[] bytes, int size)
  161. {
  162. return Sdk.HP_Server_Send(pServer, connId, bytes, size);
  163. }
  164. /// <summary>
  165. /// 发送数据
  166. /// </summary>
  167. /// <param name="connId"></param>
  168. /// <param name="bufferPtr"></param>
  169. /// <param name="size"></param>
  170. /// <returns></returns>
  171. public bool Send(IntPtr connId, IntPtr bufferPtr, int size)
  172. {
  173. return Sdk.HP_Server_Send(pServer, connId, bufferPtr, size);
  174. }
  175. /// <summary>
  176. /// 发送数据
  177. /// </summary>
  178. /// <param name="connId"></param>
  179. /// <param name="bytes"></param>
  180. /// <param name="offset">针对bytes的偏移</param>
  181. /// <param name="size">发多大</param>
  182. /// <returns></returns>
  183. public bool Send(IntPtr connId, byte[] bytes, int offset, int size)
  184. {
  185. return Sdk.HP_Server_SendPart(pServer, connId, bytes, size, offset);
  186. }
  187. /// <summary>
  188. /// 发送数据
  189. /// </summary>
  190. /// <param name="connId"></param>
  191. /// <param name="bufferPtr"></param>
  192. /// <param name="offset">针对bufferPtr的偏移</param>
  193. /// <param name="size">发多大</param>
  194. /// <returns></returns>
  195. public bool Send(IntPtr connId, IntPtr bufferPtr, int offset, int size)
  196. {
  197. return Sdk.HP_Server_SendPart(pServer, connId, bufferPtr, size, offset);
  198. }
  199. /// <summary>
  200. /// 发送数据
  201. /// </summary>
  202. /// <param name="connId"></param>
  203. /// <param name="bufferPtr"></param>
  204. /// <param name="size"></param>
  205. /// <returns></returns>
  206. public bool Send<T>(IntPtr connId, T obj)
  207. {
  208. byte[] buffer = StructureToByte<T>(obj);
  209. return Send(connId, buffer, buffer.Length);
  210. }
  211. /// <summary>
  212. /// 序列化对象后发送数据,序列化对象所属类必须标记[Serializable]
  213. /// </summary>
  214. /// <param name="connId"></param>
  215. /// <param name="bufferPtr"></param>
  216. /// <param name="size"></param>
  217. /// <returns></returns>
  218. public bool SendBySerializable(IntPtr connId, object obj)
  219. {
  220. byte[] buffer = ObjectToBytes(obj);
  221. return Send(connId, buffer, buffer.Length);
  222. }
  223. /// <summary>
  224. /// 发送多组数据
  225. /// 向指定连接发送多组数据
  226. /// TCP - 顺序发送所有数据包
  227. /// </summary>
  228. /// <param name="connId">连接 ID</param>
  229. /// <param name="pBuffers">发送缓冲区数组</param>
  230. /// <param name="iCount">发送缓冲区数目</param>
  231. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  232. public bool SendPackets(IntPtr connId, WSABUF[] pBuffers, int count)
  233. {
  234. return Sdk.HP_Server_SendPackets(pServer, connId, pBuffers, count);
  235. }
  236. /// <summary>
  237. /// 发送多组数据
  238. /// 向指定连接发送多组数据
  239. /// TCP - 顺序发送所有数据包
  240. /// </summary>
  241. /// <param name="connId">连接 ID</param>
  242. /// <param name="pBuffers">发送缓冲区数组</param>
  243. /// <param name="iCount">发送缓冲区数目</param>
  244. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  245. public bool SendPackets<T>(IntPtr connId, T[] objects)
  246. {
  247. bool ret = false;
  248. WSABUF[] buffer = new WSABUF[objects.Length];
  249. IntPtr[] ptrs = new IntPtr[buffer.Length];
  250. try
  251. {
  252. for (int i = 0; i < objects.Length; i++)
  253. {
  254. buffer[i].Length = Marshal.SizeOf(typeof(T));
  255. ptrs[i] = Marshal.AllocHGlobal(buffer[i].Length);
  256. Marshal.StructureToPtr(objects[i], ptrs[i], true);
  257. buffer[i].Buffer = ptrs[i];
  258. }
  259. ret = SendPackets(connId, buffer, buffer.Length);
  260. }
  261. catch (Exception ex)
  262. {
  263. throw ex;
  264. }
  265. finally
  266. {
  267. for (int i = 0; i < ptrs.Length; i++)
  268. {
  269. if (ptrs[i] != IntPtr.Zero)
  270. {
  271. Marshal.FreeHGlobal(ptrs[i]);
  272. }
  273. }
  274. }
  275. return ret;
  276. }
  277. /// <summary>
  278. /// 名称:发送小文件
  279. /// 描述:向指定连接发送 4096 KB 以下的小文件
  280. /// </summary>
  281. /// <param name="connId"></param>
  282. /// <param name="filePath">文件路径</param>
  283. /// <param name="head">头部附加数据</param>
  284. /// <param name="tail">尾部附加数据</param>
  285. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  286. public bool SendSmallFile(IntPtr connId, string filePath, ref WSABUF head, ref WSABUF tail)
  287. {
  288. return Sdk.HP_TcpServer_SendSmallFile(pServer, connId, filePath, ref head, ref tail);
  289. }
  290. /// <summary>
  291. /// 名称:发送小文件
  292. /// 描述:向指定连接发送 4096 KB 以下的小文件
  293. /// </summary>
  294. /// <param name="connId"></param>
  295. /// <param name="filePath">文件路径</param>
  296. /// <param name="head">头部附加数据,可以为null</param>
  297. /// <param name="tail">尾部附加数据,可以为null</param>
  298. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  299. public bool SendSmallFile(IntPtr connId, string filePath, byte[] head, byte[] tail)
  300. {
  301. IntPtr pHead = IntPtr.Zero;
  302. IntPtr pTail = IntPtr.Zero;
  303. WSABUF wsaHead = new WSABUF() { Length = 0, Buffer = pHead };
  304. WSABUF wsatail = new WSABUF() { Length = 0, Buffer = pTail };
  305. if (head != null)
  306. {
  307. wsaHead.Length = head.Length;
  308. wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(head, 0);
  309. }
  310. if (tail != null)
  311. {
  312. wsaHead.Length = tail.Length;
  313. wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(tail, 0);
  314. }
  315. return SendSmallFile(connId, filePath, ref wsaHead, ref wsatail);
  316. }
  317. /// <summary>
  318. /// 名称:发送小文件
  319. /// 描述:向指定连接发送 4096 KB 以下的小文件
  320. /// </summary>
  321. /// <param name="connId"></param>
  322. /// <param name="filePath">文件路径</param>
  323. /// <param name="head">头部附加数据,可以为null</param>
  324. /// <param name="tail">尾部附加数据,可以为null</param>
  325. /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
  326. public bool SendSmallFile<T1, T2>(IntPtr connId, string filePath, T1 head, T2 tail)
  327. {
  328. byte[] headBuffer = null;
  329. if (head != null)
  330. {
  331. headBuffer = StructureToByte<T1>(head);
  332. }
  333. byte[] tailBuffer = null;
  334. if (tail != null)
  335. {
  336. tailBuffer = StructureToByte<T2>(tail);
  337. }
  338. return SendSmallFile(connId, filePath, headBuffer, tailBuffer);
  339. }
  340. /// <summary>
  341. /// 断开与某个客户的连接
  342. /// </summary>
  343. /// <param name="connId"></param>
  344. /// <param name="bForce">是否强制断开</param>
  345. /// <returns></returns>
  346. public bool Disconnect(IntPtr connId, bool force = true)
  347. {
  348. return Sdk.HP_Server_Disconnect(pServer, connId, force);
  349. }
  350. /// <summary>
  351. /// 断开超过指定时间的连接
  352. /// </summary>
  353. /// <param name="period">毫秒</param>
  354. /// <param name="force">强制</param>
  355. /// <returns></returns>
  356. public bool DisconnectLongConnections(uint period, bool force = true)
  357. {
  358. return Sdk.HP_Server_DisconnectLongConnections(pServer, period, force);
  359. }
  360. /// <summary>
  361. /// 断开超过指定时长的静默连接
  362. /// </summary>
  363. /// <param name="period">毫秒</param>
  364. /// <param name="force">强制</param>
  365. /// <returns></returns>
  366. public bool DisconnectSilenceConnections(uint period, bool force = true)
  367. {
  368. return Sdk.HP_Server_DisconnectSilenceConnections(pServer, period, force);
  369. }
  370. /// <summary>
  371. /// 获取某个连接的远程ip和端口
  372. /// </summary>
  373. /// <param name="connId"></param>
  374. /// <param name="ip"></param>
  375. /// <param name="port"></param>
  376. /// <returns></returns>
  377. public bool GetRemoteAddress(IntPtr connId, ref string ip, ref ushort port)
  378. {
  379. int ipLength = 40;
  380. StringBuilder sb = new StringBuilder(ipLength);
  381. bool ret = Sdk.HP_Server_GetRemoteAddress(pServer, connId, sb, ref ipLength, ref port) && ipLength > 0;
  382. if (ret == true)
  383. {
  384. ip = sb.ToString();
  385. }
  386. return ret;
  387. }
  388. /// <summary>
  389. /// 获取连接中未发出数据的长度
  390. /// </summary>
  391. /// <param name="connId"></param>
  392. /// <param name="length"></param>
  393. /// <returns></returns>
  394. public bool GetPendingDataLength(IntPtr connId, ref int length)
  395. {
  396. return Sdk.HP_Server_GetPendingDataLength(pServer, connId, ref length);
  397. }
  398. /// <summary>
  399. /// 设置连接的附加数据
  400. /// </summary>
  401. /// <param name="connId"></param>
  402. /// <param name="obj">如果为null,则为释放设置的数据</param>
  403. /// <returns></returns>
  404. public bool SetConnectionExtra(IntPtr connId, object obj)
  405. {
  406. IntPtr ptr = IntPtr.Zero;
  407. // 释放附加数据
  408. if (Sdk.HP_Server_GetConnectionExtra(pServer, connId, ref ptr) && ptr != IntPtr.Zero)
  409. {
  410. Marshal.FreeHGlobal(ptr);
  411. ptr = IntPtr.Zero;
  412. }
  413. if (obj != null)
  414. {
  415. // 设置附加数据
  416. ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));
  417. Marshal.StructureToPtr(obj, ptr, false);
  418. }
  419. return Sdk.HP_Server_SetConnectionExtra(pServer, connId, ptr);
  420. }
  421. /// <summary>
  422. /// 获取附加数据
  423. /// 如设置的是个结构体/类对象,可以用 Type objA = (Type)Marshal.PtrToStructure(ptr, typeof(Type)) 获取
  424. /// 其中Type是结构体/类名,ptr是该方法的传出值,在该方法返回为true的时候可用
  425. /// </summary>
  426. /// <param name="connId"></param>
  427. /// <param name="ptr"></param>
  428. /// <returns></returns>
  429. public bool GetConnectionExtra(IntPtr connId, ref IntPtr ptr)
  430. {
  431. return Sdk.HP_Server_GetConnectionExtra(pServer, connId, ref ptr) && ptr != IntPtr.Zero;
  432. }
  433. // 是否启动
  434. public bool IsStarted
  435. {
  436. get
  437. {
  438. if (pServer == IntPtr.Zero)
  439. {
  440. return false;
  441. }
  442. return Sdk.HP_Server_HasStarted(pServer);
  443. }
  444. }
  445. /// <summary>
  446. /// 状态
  447. /// </summary>
  448. public ServiceState State
  449. {
  450. get
  451. {
  452. return Sdk.HP_Server_GetState(pServer);
  453. }
  454. }
  455. /// <summary>
  456. /// 连接数
  457. /// </summary>
  458. public uint ConnectionCount
  459. {
  460. get
  461. {
  462. return Sdk.HP_Server_GetConnectionCount(pServer);
  463. }
  464. }
  465. /// <summary>
  466. /// 获取所有连接,未获取到连接返回null
  467. /// </summary>
  468. /// <returns></returns>
  469. public IntPtr[] GetAllConnectionIDs()
  470. {
  471. IntPtr[] arr = null;
  472. do
  473. {
  474. uint count = ConnectionCount;
  475. if (count == 0)
  476. {
  477. break;
  478. }
  479. arr = new IntPtr[count];
  480. if (Sdk.HP_Server_GetAllConnectionIDs(pServer, arr, ref count))
  481. {
  482. if (arr.Length > count)
  483. {
  484. IntPtr[] newArr = new IntPtr[count];
  485. Array.Copy(arr, newArr, count);
  486. arr = newArr;
  487. }
  488. break;
  489. }
  490. } while (true);
  491. return arr;
  492. }
  493. /// <summary>
  494. /// 获取监听socket的地址信息
  495. /// </summary>
  496. /// <param name="ip"></param>
  497. /// <param name="port"></param>
  498. /// <returns></returns>
  499. public bool GetListenAddress(ref string ip, ref ushort port)
  500. {
  501. int ipLength = 40;
  502. StringBuilder sb = new StringBuilder(ipLength);
  503. bool ret = Sdk.HP_Server_GetListenAddress(pServer, sb, ref ipLength, ref port);
  504. if (ret == true)
  505. {
  506. ip = sb.ToString();
  507. }
  508. return ret;
  509. }
  510. /// <summary>
  511. /// 获取指定连接的连接时长(毫秒)
  512. /// </summary>
  513. /// <param name="connId"></param>
  514. /// <param name="period"></param>
  515. /// <returns></returns>
  516. public bool GetConnectPeriod(IntPtr connId, ref uint period)
  517. {
  518. return Sdk.HP_Server_GetConnectPeriod(pServer, connId, ref period);
  519. }
  520. /// <summary>
  521. /// 获取某个连接静默时间(毫秒)
  522. /// </summary>
  523. /// <param name="connId"></param>
  524. /// <param name="period"></param>
  525. /// <returns></returns>
  526. public bool GetSilencePeriod(IntPtr connId, ref uint period)
  527. {
  528. return Sdk.HP_Server_GetSilencePeriod(pServer, connId, ref period);
  529. }
  530. ///////////////////////////////////////////////////////////////////////////////////////
  531. /// <summary>
  532. /// 读取或设置工作线程数量(通常设置为 2 * CPU + 2)
  533. /// </summary>
  534. public uint WorkerThreadCount
  535. {
  536. get
  537. {
  538. return Sdk.HP_Server_GetWorkerThreadCount(pServer);
  539. }
  540. set
  541. {
  542. Sdk.HP_Server_SetWorkerThreadCount(pServer, value);
  543. }
  544. }
  545. /// <summary>
  546. /// 读取或设置 Accept 预投递数量(根据负载调整设置,Accept 预投递数量越大则支持的并发连接请求越多)
  547. /// </summary>
  548. public uint AcceptSocketCount
  549. {
  550. get
  551. {
  552. return Sdk.HP_TcpServer_GetAcceptSocketCount(pServer);
  553. }
  554. set
  555. {
  556. Sdk.HP_TcpServer_SetAcceptSocketCount(pServer, value);
  557. }
  558. }
  559. /// <summary>
  560. /// 读取或设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为 1024 的倍数)
  561. /// </summary>
  562. public uint SocketBufferSize
  563. {
  564. get
  565. {
  566. return Sdk.HP_TcpServer_GetSocketBufferSize(pServer);
  567. }
  568. set
  569. {
  570. Sdk.HP_TcpServer_SetSocketBufferSize(pServer, value);
  571. }
  572. }
  573. /// <summary>
  574. /// 读取或设置监听 Socket 的等候队列大小(根据并发连接数量调整设置)
  575. /// </summary>
  576. public uint SocketListenQueue
  577. {
  578. get
  579. {
  580. return Sdk.HP_TcpServer_GetSocketListenQueue(pServer);
  581. }
  582. set
  583. {
  584. Sdk.HP_TcpServer_SetSocketListenQueue(pServer, value);
  585. }
  586. }
  587. /// <summary>
  588. /// 读取或设置 Socket 缓存对象锁定时间(毫秒,在锁定期间该 Socket 缓存对象不能被获取使用)
  589. /// </summary>
  590. public uint FreeSocketObjLockTime
  591. {
  592. get
  593. {
  594. return Sdk.HP_Server_GetFreeSocketObjLockTime(pServer);
  595. }
  596. set
  597. {
  598. Sdk.HP_Server_SetFreeSocketObjLockTime(pServer, value);
  599. }
  600. }
  601. /// <summary>
  602. /// 读取或设置 Socket 缓存池大小(通常设置为平均并发连接数量的 1/3 - 1/2)
  603. /// </summary>
  604. public uint FreeSocketObjPool
  605. {
  606. get
  607. {
  608. return Sdk.HP_Server_GetFreeSocketObjPool(pServer);
  609. }
  610. set
  611. {
  612. Sdk.HP_Server_SetFreeSocketObjPool(pServer, value);
  613. }
  614. }
  615. /// <summary>
  616. /// 读取或设置内存块缓存池大小(通常设置为 Socket 缓存池大小的 2 - 3 倍)
  617. /// </summary>
  618. public uint FreeBufferObjPool
  619. {
  620. get
  621. {
  622. return Sdk.HP_Server_GetFreeBufferObjPool(pServer);
  623. }
  624. set
  625. {
  626. Sdk.HP_Server_SetFreeBufferObjPool(pServer, value);
  627. }
  628. }
  629. /// <summary>
  630. /// 读取或设置内存块缓存池大小(通常设置为 Socket 缓存池大小的 2 - 3 倍)
  631. /// </summary>
  632. public uint FreeSocketObjHold
  633. {
  634. get
  635. {
  636. return Sdk.HP_Server_GetFreeSocketObjHold(pServer);
  637. }
  638. set
  639. {
  640. Sdk.HP_Server_SetFreeSocketObjHold(pServer, value);
  641. }
  642. }
  643. /// <summary>
  644. /// 读取或设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍)
  645. /// </summary>
  646. public uint FreeBufferObjHold
  647. {
  648. get
  649. {
  650. return Sdk.HP_Server_GetFreeBufferObjHold(pServer);
  651. }
  652. set
  653. {
  654. Sdk.HP_Server_SetFreeBufferObjHold(pServer, value);
  655. }
  656. }
  657. /// <summary>
  658. /// 读取或设置心跳包间隔(毫秒,0 则不发送心跳包)
  659. /// </summary>
  660. public uint KeepAliveTime
  661. {
  662. get
  663. {
  664. return Sdk.HP_TcpServer_GetKeepAliveTime(pServer);
  665. }
  666. set
  667. {
  668. Sdk.HP_TcpServer_SetKeepAliveTime(pServer, value);
  669. }
  670. }
  671. /// <summary>
  672. /// 读取或设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线)
  673. /// </summary>
  674. public uint KeepAliveInterval
  675. {
  676. get
  677. {
  678. return Sdk.HP_TcpServer_GetKeepAliveInterval(pServer);
  679. }
  680. set
  681. {
  682. Sdk.HP_TcpServer_SetKeepAliveInterval(pServer, value);
  683. }
  684. }
  685. /// <summary>
  686. /// 读取或设置是否标记静默时间(设置为 TRUE 时 DisconnectSilenceConnections() 和 GetSilencePeriod() 才有效,默认:FALSE)
  687. /// </summary>
  688. public bool MarkSilence
  689. {
  690. get
  691. {
  692. return Sdk.HP_Server_IsMarkSilence(pServer);
  693. }
  694. set
  695. {
  696. Sdk.HP_Server_SetMarkSilence(pServer, value);
  697. }
  698. }
  699. /// <summary>
  700. /// 获取或设置数据发送策略
  701. /// </summary>
  702. public SendPolicy SendPolicy
  703. {
  704. get
  705. {
  706. return Sdk.HP_Server_GetSendPolicy(pServer);
  707. }
  708. set
  709. {
  710. Sdk.HP_Server_SetSendPolicy(pServer, value);
  711. }
  712. }
  713. ///////////////////////////////////////////////////////////////////////////////////////
  714. /// <summary>
  715. /// 获取系统返回的错误码
  716. /// </summary>
  717. public int SYSGetLastError()
  718. {
  719. return Sdk.SYS_GetLastError();
  720. }
  721. /// <summary>
  722. /// 调用系统的 ::WSAGetLastError() 方法获取通信错误代码
  723. /// </summary>
  724. public int SYSWSAGetLastError()
  725. {
  726. return Sdk.SYS_WSAGetLastError();
  727. }
  728. /// <summary>
  729. /// 获取错误码
  730. /// </summary>
  731. public SocketError ErrorCode
  732. {
  733. get
  734. {
  735. return Sdk.HP_Server_GetLastError(pServer);
  736. }
  737. }
  738. /// <summary>
  739. /// 获取错误信息
  740. /// </summary>
  741. public string ErrorMessage
  742. {
  743. get
  744. {
  745. IntPtr ptr = Sdk.HP_Server_GetLastErrorDesc(pServer);
  746. string desc = Marshal.PtrToStringUni(ptr);
  747. return desc;
  748. }
  749. }
  750. ///////////////////////////////////////////////////////////////////////////////////////
  751. Sdk.OnPrepareListen _OnPrepareListen = null;
  752. Sdk.OnAccept _OnAccept = null;
  753. Sdk.OnReceive _OnReceive = null;
  754. Sdk.OnSend _OnSend = null;
  755. Sdk.OnClose _OnClose = null;
  756. Sdk.OnShutdown _OnShutdown = null;
  757. protected virtual void SetCallback()
  758. {
  759. _OnPrepareListen = new Sdk.OnPrepareListen(SDK_OnPrepareListen);
  760. _OnAccept = new Sdk.OnAccept(SDK_OnAccept);
  761. _OnSend = new Sdk.OnSend(SDK_OnSend);
  762. _OnReceive = new Sdk.OnReceive(SDK_OnReceive);
  763. _OnClose = new Sdk.OnClose(SDK_OnClose);
  764. _OnShutdown = new Sdk.OnShutdown(SDK_OnShutdown);
  765. Sdk.HP_Set_FN_Server_OnPrepareListen(pListener, _OnPrepareListen);
  766. Sdk.HP_Set_FN_Server_OnAccept(pListener, _OnAccept);
  767. Sdk.HP_Set_FN_Server_OnSend(pListener, _OnSend);
  768. Sdk.HP_Set_FN_Server_OnReceive(pListener, _OnReceive);
  769. Sdk.HP_Set_FN_Server_OnClose(pListener, _OnClose);
  770. Sdk.HP_Set_FN_Server_OnShutdown(pListener, _OnShutdown);
  771. }
  772. protected HandleResult SDK_OnPrepareListen(IntPtr soListen)
  773. {
  774. if (OnPrepareListen != null)
  775. {
  776. return OnPrepareListen(soListen);
  777. }
  778. return HandleResult.Ignore;
  779. }
  780. protected HandleResult SDK_OnAccept(IntPtr connId, IntPtr pClient)
  781. {
  782. if (OnAccept != null)
  783. {
  784. return OnAccept(connId, pClient);
  785. }
  786. return HandleResult.Ignore;
  787. }
  788. protected HandleResult SDK_OnSend(IntPtr connId, IntPtr pData, int length)
  789. {
  790. if (OnSend != null)
  791. {
  792. byte[] bytes = new byte[length];
  793. Marshal.Copy(pData, bytes, 0, length);
  794. return OnSend(connId, bytes);
  795. }
  796. return HandleResult.Ignore;
  797. }
  798. protected HandleResult SDK_OnReceive(IntPtr connId, IntPtr pData, int length)
  799. {
  800. if (OnReceive != null)
  801. {
  802. byte[] bytes = new byte[length];
  803. Marshal.Copy(pData, bytes, 0, length);
  804. return OnReceive(connId, bytes);
  805. }
  806. return HandleResult.Ignore;
  807. }
  808. protected HandleResult SDK_OnClose(IntPtr connId, SocketOperation enOperation, int errorCode)
  809. {
  810. if (OnClose != null)
  811. {
  812. return OnClose(connId, enOperation, errorCode);
  813. }
  814. return HandleResult.Ignore;
  815. }
  816. protected HandleResult SDK_OnShutdown()
  817. {
  818. if (OnShutdown != null)
  819. {
  820. return OnShutdown();
  821. }
  822. return HandleResult.Ignore;
  823. }
  824. /////////////////////////////////////////////////////////////////////////
  825. /// <summary>
  826. /// 根据错误码返回错误信息
  827. /// </summary>
  828. /// <param name="code"></param>
  829. /// <returns></returns>
  830. public string GetSocketErrorDesc(SocketError code)
  831. {
  832. IntPtr ptr = Sdk.HP_GetSocketErrorDesc(code);
  833. string desc = Marshal.PtrToStringUni(ptr);
  834. return desc;
  835. }
  836. /// <summary>
  837. /// 调用系统的 setsockopt()
  838. /// </summary>
  839. /// <param name="sock"></param>
  840. /// <param name="level"></param>
  841. /// <param name="name"></param>
  842. /// <param name="val"></param>
  843. /// <param name="len"></param>
  844. /// <returns></returns>
  845. ///
  846. public int SYS_SetSocketOption(IntPtr sock, int level, int name, IntPtr val, int len)
  847. {
  848. return Sdk.SYS_SetSocketOption(sock, level, name, val, len);
  849. }
  850. /// <summary>
  851. /// 调用系统的 getsockopt()
  852. /// </summary>
  853. /// <param name="sock"></param>
  854. /// <param name="level"></param>
  855. /// <param name="name"></param>
  856. /// <param name="val"></param>
  857. /// <param name="len"></param>
  858. /// <returns></returns>
  859. ///
  860. public int SYSGetSocketOption(IntPtr sock, int level, int name, IntPtr val, ref int len)
  861. {
  862. return Sdk.SYS_GetSocketOption(sock, level, name, val, ref len);
  863. }
  864. /// <summary>
  865. /// 调用系统的 ioctlsocket()
  866. /// </summary>
  867. /// <param name="sock"></param>
  868. /// <param name="cmd"></param>
  869. /// <param name="arg"></param>
  870. /// <returns></returns>
  871. ///
  872. public int SYSIoctlSocket(IntPtr sock, long cmd, IntPtr arg)
  873. {
  874. return Sdk.SYS_IoctlSocket(sock, cmd, arg);
  875. }
  876. /// <summary>
  877. /// 调用系统的 ::WSAIoctl()
  878. /// </summary>
  879. /// <param name="sock"></param>
  880. /// <param name="dwIoControlCode"></param>
  881. /// <param name="lpvInBuffer"></param>
  882. /// <param name="cbInBuffer"></param>
  883. /// <param name="lpvOutBuffer"></param>
  884. /// <param name="cbOutBuffer"></param>
  885. /// <param name="lpcbBytesReturned"></param>
  886. /// <returns></returns>
  887. public int SYS_WSAIoctl(IntPtr sock, uint dwIoControlCode, IntPtr lpvInBuffer, uint cbInBuffer,
  888. IntPtr lpvOutBuffer, uint cbOutBuffer, uint lpcbBytesReturned)
  889. {
  890. return Sdk.SYS_WSAIoctl(sock, dwIoControlCode, lpvInBuffer, cbInBuffer,
  891. lpvOutBuffer, cbOutBuffer, lpcbBytesReturned);
  892. }
  893. /// <summary>
  894. /// 由结构体转换为byte数组
  895. /// </summary>
  896. public byte[] StructureToByte<T>(T structure)
  897. {
  898. int size = Marshal.SizeOf(typeof(T));
  899. byte[] buffer = new byte[size];
  900. IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
  901. try
  902. {
  903. Marshal.StructureToPtr(structure, bufferIntPtr, true);
  904. Marshal.Copy(bufferIntPtr, buffer, 0, size);
  905. }
  906. finally
  907. {
  908. Marshal.FreeHGlobal(bufferIntPtr);
  909. }
  910. return buffer;
  911. }
  912. /// <summary>
  913. /// 由byte数组转换为结构体
  914. /// </summary>
  915. public T ByteToStructure<T>(byte[] dataBuffer)
  916. {
  917. object structure = null;
  918. int size = Marshal.SizeOf(typeof(T));
  919. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  920. try
  921. {
  922. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  923. structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
  924. }
  925. finally
  926. {
  927. Marshal.FreeHGlobal(allocIntPtr);
  928. }
  929. return (T)structure;
  930. }
  931. /// <summary>
  932. /// 对象序列化成byte[]
  933. /// </summary>
  934. /// <param name="obj"></param>
  935. /// <returns></returns>
  936. public byte[] ObjectToBytes(object obj)
  937. {
  938. using (MemoryStream ms = new MemoryStream())
  939. {
  940. IFormatter formatter = new BinaryFormatter();
  941. formatter.Serialize(ms, obj);
  942. return ms.GetBuffer();
  943. }
  944. }
  945. /// <summary>
  946. /// byte[]序列化成对象
  947. /// </summary>
  948. /// <param name="Bytes"></param>
  949. /// <returns></returns>
  950. public object BytesToObject(byte[] bytes)
  951. {
  952. using (MemoryStream ms = new MemoryStream(bytes))
  953. {
  954. IFormatter formatter = new BinaryFormatter();
  955. return formatter.Deserialize(ms);
  956. }
  957. }
  958. /// <summary>
  959. /// byte[]转结构体
  960. /// </summary>
  961. /// <typeparam name="T"></typeparam>
  962. /// <param name="bytes"></param>
  963. /// <returns></returns>
  964. public T BytesToStruct<T>(byte[] bytes)
  965. {
  966. Type strcutType = typeof(T);
  967. int size = Marshal.SizeOf(strcutType);
  968. IntPtr buffer = Marshal.AllocHGlobal(size);
  969. try
  970. {
  971. Marshal.Copy(bytes, 0, buffer, size);
  972. return (T)Marshal.PtrToStructure(buffer, strcutType);
  973. }
  974. finally
  975. {
  976. Marshal.FreeHGlobal(buffer);
  977. }
  978. }
  979. #region 扩展代码
  980. /// <summary>
  981. /// 获取客户端信息
  982. /// </summary>
  983. /// <param name="connId"></param>
  984. /// <returns></returns>
  985. public HPSocketCS.Extended.ClientInfo GetClientInfo(IntPtr connId)
  986. {
  987. // 获取附加数据
  988. IntPtr clientPtr = IntPtr.Zero;
  989. if (!this.GetConnectionExtra(connId, ref clientPtr))
  990. {
  991. clientPtr = IntPtr.Zero;
  992. }
  993. HPSocketCS.Extended.ClientInfo ci = null;
  994. try
  995. {
  996. // IntPtr.Zero;
  997. // ci 就是accept里传入的附加数据了
  998. if (clientPtr != IntPtr.Zero)
  999. {
  1000. ci = (HPSocketCS.Extended.ClientInfo)Marshal.PtrToStructure(clientPtr, typeof(HPSocketCS.Extended.ClientInfo));
  1001. }
  1002. }
  1003. catch { }
  1004. return ci;
  1005. }
  1006. CommonLibrary _SCommonLibrary = new CommonLibrary();
  1007. /// <summary>
  1008. /// 服务端扩展处理类
  1009. /// </summary>
  1010. public CommonLibrary SCommonLibrary
  1011. {
  1012. get { return _SCommonLibrary; }
  1013. }
  1014. /// <summary>
  1015. /// 获取数据包最大长度
  1016. /// </summary>
  1017. /// <param name="pClient"></param>
  1018. /// <returns></returns>
  1019. public int GetMaxPackSize(IntPtr pClient)
  1020. {
  1021. return Convert.ToInt32(Sdk.HP_TcpPackClient_GetMaxPackSize(pClient));
  1022. }
  1023. /// <summary>
  1024. /// 自动拆包并发送
  1025. /// </summary>
  1026. /// <param name="client">客户端连接对象</param>
  1027. /// <param name="bytes">要发送的数据</param>
  1028. /// <param name="generateId">本次发送数据时的唯一ID</param>
  1029. /// <returns></returns>
  1030. public bool AutoUnpackingAndSend(IntPtr connId, byte[] bytes, Int64 generateId, DataType dType, TransferRequestCommand requestCommand)
  1031. {
  1032. bool retbl = false;
  1033. // 获取附加数据
  1034. IntPtr clientPtr = IntPtr.Zero;
  1035. if (!this.GetConnectionExtra(connId, ref clientPtr))
  1036. {
  1037. clientPtr = IntPtr.Zero;
  1038. }
  1039. TcpHeadInfo appendifo = CommonLibrary.GetProtocolHeader(connId, clientPtr, dType, requestCommand, generateId);
  1040. int sendMaxPackSize = GetMaxPackSize(this.pServer);
  1041. // List<byte[]> sendPakByteList = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, appendifo,new TcpTailInfo(), GetMaxPackSize(this.pServer));
  1042. System.IO.BufferedStream sendMsstream = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, appendifo, new TcpTailInfo(), sendMaxPackSize);
  1043. try
  1044. {
  1045. int bytesRead = 0;
  1046. long totalBytes = 0;
  1047. do
  1048. {
  1049. byte[] sendFileBytes = null;
  1050. if (sendMsstream.Length - totalBytes > sendMaxPackSize)
  1051. {
  1052. sendFileBytes = new byte[sendMaxPackSize];
  1053. }
  1054. else
  1055. {
  1056. sendFileBytes = new byte[Convert.ToInt32(sendMsstream.Length - totalBytes)];
  1057. }
  1058. bytesRead = sendMsstream.Read(sendFileBytes, 0, sendFileBytes.Length);
  1059. if (bytesRead > 0)
  1060. {
  1061. totalBytes += bytesRead;
  1062. // 发送
  1063. if (this.Send(connId, sendFileBytes, sendFileBytes.Length))
  1064. {
  1065. retbl = true;
  1066. }
  1067. else
  1068. {
  1069. retbl = false;
  1070. break;
  1071. }
  1072. System.Threading.Thread.Sleep(1);
  1073. }
  1074. Array.Clear(sendFileBytes, 0, sendFileBytes.Length);
  1075. System.GC.Collect();
  1076. } while (bytesRead > 0);
  1077. }
  1078. catch { }
  1079. finally
  1080. {
  1081. sendMsstream.Close();
  1082. sendMsstream.Dispose();
  1083. sendMsstream = null;
  1084. }
  1085. System.GC.Collect();
  1086. return retbl;
  1087. }
  1088. /// <summary>
  1089. /// 服务器端接收客户端发送的文本数据请求并处理返回结果
  1090. /// </summary>
  1091. /// <param name="header">协议头</param>
  1092. /// <param name="connId">连接ID</param>
  1093. /// <param name="bytes">收到的数据</param>
  1094. public bool DataTypeTextProcessed(TcpHeadInfo header,IntPtr connId, byte[] bytes)
  1095. {
  1096. bool ret = false;
  1097. string ReceiveInfo = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
  1098. TransferRequestCommand Command = (TransferRequestCommand)Convert.ToInt32(header.RequestCommand);
  1099. string returnInfo = "";
  1100. try
  1101. {
  1102. // LYFZ.BLL.BLL_FileLogs.WriteMainLogs(String.Format("接收到命令请求{0},参数{1}", Command.ToString(), ReceiveInfo));
  1103. switch (Command)
  1104. {
  1105. case TransferRequestCommand.Message:
  1106. returnInfo = "服务器已接收到:" + ReceiveInfo + "...";
  1107. break;
  1108. default:
  1109. returnInfo ="非法指令,服务器拒绝执行...";
  1110. break;
  1111. }
  1112. }
  1113. catch (Exception ex)
  1114. {
  1115. returnInfo = "网络请求处理失败,原因:" + ex.Message;
  1116. }
  1117. byte[] sendBytes = Encoding.UTF8.GetBytes(returnInfo);
  1118. ret = AutoUnpackingAndSend(connId, sendBytes, header.TransportID, DataType.Text, Command);
  1119. return ret;
  1120. }
  1121. #region 发送/接收文件
  1122. static HPSocketCS.TcpPackClient hpCloudClient;
  1123. /// <summary>
  1124. /// 网络对象
  1125. /// </summary>
  1126. [Obsolete("此属性只用于“云服务器文件传”类,请不要在其它地方使用", false)]
  1127. public static HPSocketCS.TcpPackClient HpCloudClient
  1128. {
  1129. get { return hpCloudClient; }
  1130. set { hpCloudClient = value; }
  1131. }
  1132. static string _EnterpriseID = "";
  1133. /// <summary>
  1134. /// 企业ID
  1135. /// </summary>
  1136. public static string EnterpriseID
  1137. {
  1138. get { return TcpServer._EnterpriseID; }
  1139. set { TcpServer._EnterpriseID = value; }
  1140. }
  1141. static string _VerificationCode = "";
  1142. /// <summary>
  1143. /// 验证码
  1144. /// </summary>
  1145. public static string VerificationCode
  1146. {
  1147. get { return TcpServer._VerificationCode; }
  1148. set { TcpServer._VerificationCode = value; }
  1149. }
  1150. static string _ServerFileDirPath = "";
  1151. /// <summary>
  1152. /// 服务器上文件保存路径
  1153. /// </summary>
  1154. public static string ServerFileDirPath
  1155. {
  1156. get { return TcpServer._ServerFileDirPath; }
  1157. set { TcpServer._ServerFileDirPath = value; }
  1158. }
  1159. /// <summary>
  1160. /// 处理请求文件路径
  1161. /// </summary>
  1162. /// <param name="requestFileString"></param>
  1163. /// <returns></returns>
  1164. public static string GetRequestFileName(string requestFileString)
  1165. {
  1166. string retFilePath = "";
  1167. if (!String.IsNullOrEmpty(requestFileString.Trim()))
  1168. {
  1169. if (requestFileString.Contains(':'))
  1170. {
  1171. retFilePath = requestFileString.Split('|')[0].Trim('\\');
  1172. }
  1173. else
  1174. {
  1175. string[] tempValues = requestFileString.Split('|');
  1176. if (!String.IsNullOrEmpty(ServerFileDirPath) && !(requestFileString.ToLower().Contains("UpdateTemp".ToLower()) && requestFileString.ToLower().Contains("ClientNewLatestVersion".ToLower())))
  1177. {
  1178. if (tempValues.Length >= 2)
  1179. {
  1180. retFilePath = CommonLibrary.GetFullDirectoryPath(ServerFileDirPath) + tempValues[1] + "\\" + tempValues[0].Trim('\\');
  1181. }
  1182. }
  1183. else {
  1184. retFilePath = CommonLibrary.GetFullDirectoryPath(CommonLibrary.BasePath) + tempValues[0].Trim('\\');
  1185. }
  1186. }
  1187. }
  1188. return retFilePath;
  1189. }
  1190. /// <summary>
  1191. /// 上传到云服务器文件过虑器
  1192. /// </summary>
  1193. /// <param name="filePath"></param>
  1194. /// <returns></returns>
  1195. public static bool CloudServerFilter(string filePath)
  1196. {
  1197. if (filePath.ToLower().Contains("来电精灵录音".ToLower()) && filePath.ToLower().Contains("ShareDirectory".ToLower()))
  1198. {
  1199. return false;
  1200. }
  1201. //医院跟踪系统相片
  1202. if (filePath.ToLower().Contains("HospitalPhotos".ToLower()) && filePath.ToLower().Contains("UploadFiles".ToLower()))
  1203. {
  1204. return false;
  1205. }
  1206. //证件照
  1207. if (filePath.ToLower().Contains("OtherConsumePhotos".ToLower()) && filePath.ToLower().Contains("UploadFiles".ToLower()))
  1208. {
  1209. return false;
  1210. }
  1211. //礼服务图片
  1212. if (filePath.ToLower().Contains("DressPhotos".ToLower()) && filePath.ToLower().Contains("UploadFiles".ToLower()))
  1213. {
  1214. return false;
  1215. }
  1216. return true;
  1217. }
  1218. /// <summary>
  1219. /// 上传到云服务器
  1220. /// </summary>
  1221. /// <param name="tail"></param>
  1222. /// <param name="receiveBytes"></param>
  1223. /// <returns></returns>
  1224. bool UploadToCloudServer(TcpHeadInfo header, TcpTailInfo tail, byte[] receiveBytes)
  1225. {
  1226. try
  1227. {
  1228. bool retbl = false;
  1229. if (hpCloudClient == null)
  1230. {
  1231. return false;
  1232. }
  1233. else if (hpCloudClient.State == ServiceState.Stoped)
  1234. {
  1235. hpCloudClient.Connetion();
  1236. }
  1237. if (receiveBytes.Length == 0)
  1238. {
  1239. return false;
  1240. }
  1241. int sendMaxPackSize = GetMaxPackSize(this.pServer);
  1242. if (!String.IsNullOrEmpty(EnterpriseID))
  1243. {
  1244. tail.FileName = tail.FileName + "|" + EnterpriseID;
  1245. }
  1246. if (!CloudServerFilter(tail.FileName))
  1247. {
  1248. return false;
  1249. }
  1250. System.IO.BufferedStream sendMsstream = CommonLibrary.AutoUnpackingAndAddPkgHeader(receiveBytes, header, tail, sendMaxPackSize);
  1251. try
  1252. {
  1253. int bytesRead = 0;
  1254. long totalBytes = 0;
  1255. do
  1256. {
  1257. byte[] sendDataBytes = null;
  1258. if (sendMsstream.Length - totalBytes > sendMaxPackSize)
  1259. {
  1260. sendDataBytes = new byte[sendMaxPackSize];
  1261. }
  1262. else
  1263. {
  1264. sendDataBytes = new byte[Convert.ToInt32(sendMsstream.Length - totalBytes)];
  1265. }
  1266. bytesRead = sendMsstream.Read(sendDataBytes, 0, sendDataBytes.Length);
  1267. if (bytesRead > 0)
  1268. {
  1269. totalBytes += bytesRead;
  1270. // 发送
  1271. if (hpCloudClient.Send(sendDataBytes, sendDataBytes.Length))
  1272. {
  1273. retbl = true;
  1274. }
  1275. else
  1276. {
  1277. retbl = false;
  1278. break;
  1279. }
  1280. System.Threading.Thread.Sleep(1);
  1281. }
  1282. Array.Clear(sendDataBytes, 0, sendDataBytes.Length);
  1283. System.GC.Collect();
  1284. } while (bytesRead > 0);
  1285. }
  1286. catch { }
  1287. finally
  1288. {
  1289. sendMsstream.Close();
  1290. sendMsstream.Dispose();
  1291. sendMsstream = null;
  1292. }
  1293. System.GC.Collect();
  1294. return retbl;
  1295. }
  1296. catch {
  1297. return false;
  1298. }
  1299. }
  1300. /// <summary>
  1301. /// 从云服务器下载文件
  1302. /// </summary>
  1303. /// <param name="fileName"></param>
  1304. /// <param name="saveFilePath"></param>
  1305. /// <returns></returns>
  1306. bool DownloadFileFromCloudServer(string fileName, string saveFilePath)
  1307. {
  1308. try
  1309. {
  1310. //从云服务器获取要下载的文件信息
  1311. if (hpCloudClient == null)
  1312. {
  1313. return false;
  1314. }
  1315. else if (hpCloudClient.State == ServiceState.Stoped)
  1316. {
  1317. hpCloudClient.Connetion();
  1318. }
  1319. HPSocketCS.Extended.RequestData requestData = new HPSocketCS.Extended.RequestData((int)HPSocketCS.Extended.TransferRequestCommand.GetFileInfo);
  1320. HPSocketCS.Extended.RequestParameters reqParameters = new RequestParameters();
  1321. reqParameters.SetRequsetEnterpriseIDParameter(EnterpriseID);
  1322. reqParameters.SetRequsetErpInstallationVerificationCodeParameter(VerificationCode);
  1323. reqParameters.SetRequestParameter<string>("FilePath", fileName);
  1324. requestData.AttachedData = reqParameters.ToBytes();
  1325. HPSocketCS.Extended.ReturnData returnData = HPSocketCS.Extended.SerializerDataProcessed.HP_SendSerializerCommandToServer(hpCloudClient, requestData);
  1326. if (returnData.ReturnStatus)
  1327. {
  1328. string fileJson = returnData.DataByteToModelObject<string>();
  1329. HPSocketCS.Extended.NetFileInfo fileInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<HPSocketCS.Extended.NetFileInfo>(fileJson);
  1330. string downloadFileNameString = fileName;
  1331. if (!String.IsNullOrEmpty(EnterpriseID))
  1332. {
  1333. downloadFileNameString = fileName + "|" + EnterpriseID;
  1334. }
  1335. if (fileInfo.IsExists && !String.IsNullOrEmpty(fileInfo.FileMd5.Trim()) && System.IO.File.Exists(saveFilePath))
  1336. {
  1337. string saveFileMd5 = HPSocketCS.Extended.CommonLibrary.GetMD5HashFromFile(saveFilePath);
  1338. if (HPSocketCS.Extended.CommonLibrary.VerifyMd5Hash(fileInfo.FileMd5.Trim(), saveFileMd5))
  1339. {
  1340. return true;
  1341. }
  1342. else
  1343. {
  1344. //如果需要下载,则开始下载
  1345. return hpCloudClient.DownloadFiles(downloadFileNameString, saveFilePath, null);
  1346. }
  1347. }
  1348. else if (fileInfo.IsExists)
  1349. {
  1350. //开始下载
  1351. return hpCloudClient.DownloadFiles(downloadFileNameString, saveFilePath, null);
  1352. }
  1353. else
  1354. {
  1355. return false;
  1356. }
  1357. }
  1358. else
  1359. {
  1360. return false;
  1361. }
  1362. }
  1363. catch
  1364. {
  1365. return false;
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// 接收文件到服务器指定目录
  1370. /// </summary>
  1371. /// <param name="tail"></param>
  1372. /// <param name="receiveBytes"></param>
  1373. /// <returns></returns>
  1374. public bool ReceiveFileToServerRootDirectory(TcpTailInfo tail, byte[] receiveBytes)
  1375. {
  1376. return ReceiveFileToServerRootDirectory(new TcpHeadInfo(), tail, receiveBytes);
  1377. }
  1378. /// <summary>
  1379. /// 接收文件到服务器指定目录
  1380. /// </summary>
  1381. /// <param name="tail"></param>
  1382. /// <param name="receiveBytes"></param>
  1383. /// <returns></returns>
  1384. public bool ReceiveFileToServerRootDirectory(TcpHeadInfo header, TcpTailInfo tail, byte[] receiveBytes)
  1385. {
  1386. bool retBl = false;
  1387. if (String.IsNullOrEmpty(tail.FileName))
  1388. {
  1389. return false;
  1390. }
  1391. try
  1392. {
  1393. string saveFilePath = GetRequestFileName(tail.FileName);
  1394. string saveDirPath = System.IO.Path.GetDirectoryName(saveFilePath);
  1395. if (!System.IO.Directory.Exists(saveDirPath))
  1396. {
  1397. try
  1398. {
  1399. System.IO.Directory.CreateDirectory(saveDirPath);
  1400. }
  1401. catch { }
  1402. }
  1403. FileStream fs = new FileStream(saveFilePath, (FileMode)tail.FileMode, FileAccess.Write);
  1404. System.IO.BufferedStream buffStream = new BufferedStream(fs, Sdk.PacketBufferSize*2);
  1405. try
  1406. {
  1407. buffStream.Write(receiveBytes, 0, receiveBytes.Length);
  1408. buffStream.Flush();
  1409. retBl = true;
  1410. }
  1411. finally
  1412. {
  1413. this.UploadToCloudServer(header, tail, receiveBytes);
  1414. buffStream.Close();
  1415. buffStream.Dispose();
  1416. buffStream = null;
  1417. fs.Close();
  1418. fs.Dispose();
  1419. fs = null;
  1420. }
  1421. }
  1422. catch { retBl = false; }
  1423. return retBl;
  1424. }
  1425. /// <summary>
  1426. /// 发送文件到客户端
  1427. /// </summary>
  1428. /// <param name="header"></param>
  1429. /// <param name="tail"></param>
  1430. /// <param name="connId"></param>
  1431. /// <returns></returns>
  1432. public bool SenFileToClient(TcpHeadInfo header,TcpTailInfo tail,IntPtr connId)
  1433. {
  1434. bool retBl = false;
  1435. if (String.IsNullOrEmpty(tail.FileName))
  1436. {
  1437. return false;
  1438. }
  1439. try
  1440. {
  1441. string tempFilePath = tail.FileName.Split('|')[0].Trim('\\');
  1442. string sendFilePath = GetRequestFileName(tail.FileName);
  1443. this.DownloadFileFromCloudServer(tempFilePath,sendFilePath);
  1444. if (System.IO.File.Exists(sendFilePath))
  1445. {
  1446. FileInfo fi = new FileInfo(sendFilePath);
  1447. tail.FileSize = fi.Length;
  1448. // 创建文件流
  1449. FileStream fs = new FileStream(sendFilePath, FileMode.Open, FileAccess.Read);//, FileShare.Read
  1450. System.IO.BufferedStream buffStream = new BufferedStream(fs, Sdk.PacketBufferSize * 2);
  1451. try
  1452. {
  1453. int Subcontract = Sdk.PacketBufferSize;//分包大小
  1454. int bytesRead = 0;
  1455. long totalBytes = 0;
  1456. do
  1457. {
  1458. byte[] sendFileBytes = null;
  1459. if (fi.Length - totalBytes > Subcontract)
  1460. {
  1461. sendFileBytes = new byte[Subcontract];
  1462. }
  1463. else
  1464. {
  1465. sendFileBytes = new byte[Convert.ToInt32(fi.Length - totalBytes)];
  1466. }
  1467. bytesRead = buffStream.Read(sendFileBytes, 0, sendFileBytes.Length);
  1468. if (bytesRead > 0)
  1469. {
  1470. if (totalBytes <= 0)
  1471. {
  1472. tail.FileMode = (int)FileMode.Create;
  1473. }
  1474. else
  1475. {
  1476. tail.FileMode = (int)FileMode.Append;
  1477. }
  1478. totalBytes += bytesRead;
  1479. if (totalBytes >= tail.FileSize)
  1480. {
  1481. tail.IsSendComplete = true;
  1482. }
  1483. else
  1484. {
  1485. tail.IsSendComplete = false;
  1486. }
  1487. retBl = SendFiles(connId, header, tail, sendFileBytes);
  1488. }
  1489. Array.Clear(sendFileBytes, 0, sendFileBytes.Length);
  1490. System.GC.Collect();
  1491. } while (bytesRead > 0);
  1492. }
  1493. catch
  1494. {
  1495. }
  1496. finally {
  1497. buffStream.Close();
  1498. buffStream.Dispose();
  1499. buffStream = null;
  1500. fs.Close();
  1501. fs.Dispose();
  1502. fs = null;
  1503. }
  1504. }
  1505. }
  1506. catch { retBl = false; }
  1507. return retBl;
  1508. }
  1509. /// <summary>
  1510. /// 发送文件字节数组
  1511. /// </summary>
  1512. /// <param name="connId"></param>
  1513. /// <param name="header"></param>
  1514. /// <param name="tail"></param>
  1515. /// <param name="toServerFileName">要保存的文件名或路径</param>
  1516. /// <param name="backgroundWorker"></param>
  1517. /// <param name="mode">文件打开方式</param>
  1518. /// <returns></returns>
  1519. public bool SendFiles(IntPtr connId, TcpHeadInfo header, TcpTailInfo tail, byte[] sendFileBytes)
  1520. {
  1521. bool retbl = false;
  1522. if (sendFileBytes.Length == 0)
  1523. {
  1524. throw new Exception("要发送的文件大小不能为0。");
  1525. }
  1526. int sendMaxPackSize = GetMaxPackSize(this.pServer);
  1527. System.IO.BufferedStream sendMsstream = CommonLibrary.AutoUnpackingAndAddPkgHeader(sendFileBytes, header, tail, sendMaxPackSize);
  1528. try
  1529. {
  1530. int bytesRead = 0;
  1531. long totalBytes = 0;
  1532. do
  1533. {
  1534. byte[] sendDataBytes = null;
  1535. if (sendMsstream.Length - totalBytes > sendMaxPackSize)
  1536. {
  1537. sendDataBytes = new byte[sendMaxPackSize];
  1538. }
  1539. else
  1540. {
  1541. sendDataBytes = new byte[Convert.ToInt32(sendMsstream.Length - totalBytes)];
  1542. }
  1543. bytesRead = sendMsstream.Read(sendDataBytes, 0, sendDataBytes.Length);
  1544. if (bytesRead > 0)
  1545. {
  1546. totalBytes += bytesRead;
  1547. // 发送
  1548. if (this.Send(connId, sendDataBytes, sendDataBytes.Length))
  1549. {
  1550. retbl = true;
  1551. }
  1552. else
  1553. {
  1554. retbl = false;
  1555. break;
  1556. }
  1557. System.Threading.Thread.Sleep(1);
  1558. }
  1559. Array.Clear(sendDataBytes, 0, sendDataBytes.Length);
  1560. System.GC.Collect();
  1561. } while (bytesRead > 0);
  1562. }
  1563. catch { }
  1564. finally {
  1565. sendMsstream.Close();
  1566. sendMsstream.Dispose();
  1567. sendMsstream = null;
  1568. }
  1569. System.GC.Collect();
  1570. return retbl;
  1571. }
  1572. #endregion
  1573. #endregion
  1574. }
  1575. }