TCP_NetworkClient.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using System.IO;
  8. using LYFZ.Network.EnumerateLibrary;
  9. using System.ComponentModel;
  10. using HPSocketCS.Extended;
  11. using System.Runtime.InteropServices;
  12. namespace LYFZ.Network.TCPNetworkClient
  13. {
  14. /// <summary>
  15. /// TCP网络通信客户端
  16. /// </summary>
  17. public class TCP_NetworkClient
  18. {
  19. public TCP_NetworkClient() {
  20. }
  21. #region 网络客户端程序处理代码
  22. TCP_NetworkClient tFileClient=null;
  23. /// <summary>
  24. /// 文件传送通道
  25. /// </summary>
  26. public TCP_NetworkClient TFileClient
  27. {
  28. get {
  29. if (this.tFileClient == null)
  30. {
  31. this.tFileClient = new TCP_NetworkClient();
  32. }
  33. return this.tFileClient;
  34. }
  35. }
  36. private AppState appState = AppState.Stoped;
  37. /// <summary>
  38. /// 当前网络状态
  39. /// </summary>
  40. public AppState AppState
  41. {
  42. get { return appState; }
  43. set { appState = value; }
  44. }
  45. // private delegate void ConnectUpdateUiDelegate();
  46. // private delegate void SetAppStateDelegate(AppState state);
  47. HPSocketCS.TcpPackClient client = new HPSocketCS.TcpPackClient();
  48. /// <summary>
  49. /// 客户端连接
  50. /// </summary>
  51. public HPSocketCS.TcpPackClient Client
  52. {
  53. get { return client; }
  54. }
  55. /// <summary>
  56. /// 连接服务器
  57. /// </summary>
  58. /// <param name="ip">ip</param>
  59. /// <param name="port">端口</param>
  60. /// <param name="isAsyncConn">是否异步连接</param>
  61. /// <returns></returns>
  62. public bool ConnectionServer(string hostOrIP="", ushort port=0, bool isAsyncConn = false)
  63. {
  64. try
  65. {
  66. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  67. {
  68. return true;
  69. }
  70. if (!this.isInitializesNetwork)
  71. {
  72. this.InitializesNetwork();
  73. }
  74. bool cAsyncConn = isAsyncConn;
  75. // 写在这个位置是上面可能会异常
  76. SetAppState(AppState.Starting);
  77. // AddMsg(string.Format("$Client Starting ... -> ({0}:{1})", ip, port));
  78. SystemFileLogs.WriteLogs(string.Format("客户端开始连接... -> ({0}:{1})", hostOrIP, port));
  79. if (client.Connetion(hostOrIP, port, cAsyncConn))
  80. {
  81. if (cAsyncConn == false)
  82. {
  83. SetAppState(AppState.Started);
  84. }
  85. this.Wapper = new TCP_RemoteDataHandlerPassiveMode(client);
  86. // AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
  87. SystemFileLogs.WriteLogs(string.Format("客户端连接OK -> ({0}:{1})", hostOrIP, port));
  88. return true;
  89. }
  90. else
  91. {
  92. SetAppState(AppState.Stoped);
  93. throw new Exception(string.Format("客户端连接出错 -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  94. }
  95. }
  96. catch (Exception ex)
  97. {
  98. SystemFileLogs.WriteLogs(string.Format("客户端连接失败-> ({0})", ex.Message));
  99. }
  100. return false;
  101. }
  102. /// <summary>
  103. /// 关闭客户端连接
  104. /// </summary>
  105. /// <returns></returns>
  106. public bool CloseConnected()
  107. {
  108. // 停止服务
  109. SystemFileLogs.WriteLogs(string.Format("准备关闭客户端连接"));
  110. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  111. {
  112. if (client.Stop())
  113. {
  114. SetAppState(AppState.Stoped);
  115. if (this.tFileClient != null && this.tFileClient.AppState == HPSocketCS.Extended.AppState.Started)
  116. {
  117. this.tFileClient.CloseConnected();
  118. }
  119. return true;
  120. }
  121. else
  122. {
  123. // AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  124. SystemFileLogs.WriteLogs(string.Format("关闭客户端连接失败-> {0}({1})", client.ErrorMessage, client.ErrorCode));
  125. }
  126. }
  127. else {
  128. return true;
  129. }
  130. return false;
  131. }
  132. bool isInitializesNetwork = false;
  133. /// <summary>
  134. /// 网络服务是否已初始化
  135. /// </summary>
  136. public bool IsInitializesNetwork
  137. {
  138. get { return isInitializesNetwork; }
  139. set { isInitializesNetwork = value; }
  140. }
  141. /// <summary>
  142. /// 申明委托
  143. /// </summary>
  144. /// <param name="e"></param>
  145. /// <returns></returns>
  146. public delegate void EventVerifiedHandler(LYFZ.Network.TCPNetworkServer.EventLockVerified e);
  147. /// <summary>
  148. /// EventClientLockVerified事件
  149. /// </summary>
  150. public event EventVerifiedHandler EventClientVerified;
  151. /// <summary>
  152. /// 初始化网络
  153. /// </summary>
  154. void InitializesNetwork()
  155. {
  156. try
  157. {
  158. // 设置client事件
  159. client.OnPrepareConnect += new HPSocketCS.TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
  160. client.OnConnect += new HPSocketCS.TcpClientEvent.OnConnectEventHandler(OnConnect);
  161. client.OnSend += new HPSocketCS.TcpClientEvent.OnSendEventHandler(OnSend);
  162. client.OnReceive += new HPSocketCS.TcpClientEvent.OnReceiveEventHandler(OnReceive);
  163. client.OnClose += new HPSocketCS.TcpClientEvent.OnCloseEventHandler(OnClose);
  164. // 设置包头标识,与对端设置保证一致性
  165. client.PackHeaderFlag = 0x1ff;
  166. // 设置最大封包大小
  167. client.MaxPackSize = 0x2000 * 32;
  168. client.SocketBufferSize = 512 * 1024;//client.MaxPackSize;
  169. SystemFileLogs.WriteLogs("客户初始化网络成功");
  170. SetAppState(AppState.Stoped);
  171. this.isInitializesNetwork = true;
  172. }
  173. catch (Exception ex)
  174. {
  175. SetAppState(AppState.Error);
  176. // AddMsg(ex.Message);
  177. SystemFileLogs.WriteLogs("客户初始化网络时出错:" + ex.Message);
  178. }
  179. }
  180. HPSocketCS.HandleResult OnPrepareConnect(HPSocketCS.TcpClient sender, uint socket)
  181. {
  182. return HPSocketCS.HandleResult.Ok;
  183. }
  184. HPSocketCS.HandleResult OnConnect(HPSocketCS.TcpClient sender)
  185. {
  186. // 已连接 到达一次
  187. // 设置附加数据
  188. string ip = "";
  189. ushort port = 0;
  190. if (sender.GetListenAddress(ref ip, ref port))
  191. {
  192. HPSocketCS.Extended.ClientInfo ci = new HPSocketCS.Extended.ClientInfo();
  193. ci.ConnId = sender.ConnectionId;
  194. ci.IpAddress = ip;
  195. ci.Port = port;
  196. sender.SetExtra(ci);
  197. }
  198. // 如果是异步联接,更新界面状态
  199. // this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));
  200. // AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));
  201. SystemFileLogs.WriteLogs("已连接:" + ip + ":" + port.ToString());
  202. return HPSocketCS.HandleResult.Ok;
  203. }
  204. HPSocketCS.HandleResult OnSend(HPSocketCS.TcpClient sender, byte[] bytes)
  205. {
  206. // 客户端发数据了
  207. //AddMsg(string.Format(" > [{0},OnSend] ->数据发送成功 ({1} bytes)", sender.ConnectionId, bytes.Length));
  208. return HPSocketCS.HandleResult.Ok;
  209. }
  210. HPSocketCS.HandleResult OnReceive(HPSocketCS.TcpClient sender, byte[] bytes)
  211. {
  212. // 数据到达了
  213. try
  214. {
  215. //收到的数据
  216. byte[] receiveBytes = new byte[0];
  217. TcpHeadInfo header = sender.BytesToStruct<TcpHeadInfo>(bytes);
  218. try
  219. {
  220. DataType dType = (DataType)header.MsgDataType;
  221. int headSize = Marshal.SizeOf(header);
  222. TcpTailInfo tail = new TcpTailInfo();
  223. if (header.IsTail)
  224. {
  225. //有附加尾数据时
  226. int tailSize = Marshal.SizeOf(tail);
  227. byte[] tailBytes = new byte[tailSize];
  228. Array.ConstrainedCopy(bytes, bytes.Length - tailSize, tailBytes, 0, tailBytes.Length);
  229. tail = sender.BytesToStruct<TcpTailInfo>(tailBytes);
  230. receiveBytes = new byte[bytes.Length - headSize - tailSize];
  231. Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
  232. tailBytes = null;
  233. }
  234. else
  235. {
  236. // 因为没有附加尾数据,所以大小可以用length - objSize
  237. receiveBytes = new byte[bytes.Length - headSize];
  238. Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
  239. }
  240. ReceiveCacheBuffer recBuffer = sender.CCommonLibrary.GetReceiveCacheBuffer(header.TransportID);
  241. if (recBuffer != null)
  242. {
  243. lock (recBuffer)
  244. {
  245. recBuffer.Length += receiveBytes.Length;
  246. if (recBuffer.BackgroundWorker != null)
  247. {
  248. //总计数器
  249. long sumCount = header.IntactSize;
  250. if (dType == DataType.File)
  251. {
  252. sumCount = tail.FileSize;
  253. }
  254. //当前计数器
  255. long currentCount = recBuffer.Length;
  256. if (header.TransportEnd && tail.IsSendComplete)
  257. {
  258. currentCount = Convert.ToInt64(sumCount);
  259. }
  260. CommonLibrary.SetBackgroundWorker(sumCount, currentCount,"正在接收数据,请稍等...", recBuffer.BackgroundWorker);
  261. }
  262. }
  263. }
  264. //接收到的客户端发送来的数据
  265. byte[] recbytes = null;
  266. try
  267. {
  268. if (header.TransportStart && header.TransportEnd)
  269. {
  270. recbytes = receiveBytes;
  271. receiveBytes = null;
  272. }
  273. else
  274. {
  275. ReceiveData rData = sender.CCommonLibrary.GetReceiveData(header);
  276. if (rData == null)
  277. {
  278. rData = new ReceiveData();
  279. sender.CCommonLibrary.AddReceiveData(rData);
  280. }
  281. rData.ReceiveRemoteClientInfo = header;
  282. rData.ReceiveDataMstream.Write(receiveBytes, 0, receiveBytes.Length);
  283. if (header.TransportEnd)
  284. {
  285. recbytes = rData.ReceiveDataMstream.ToArray();
  286. sender.CCommonLibrary.RemoveReceiveDataData(rData);
  287. }
  288. }
  289. if (recbytes != null)
  290. {
  291. recbytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(recbytes);
  292. if (!header.IsTail && header.TransportEnd)
  293. {
  294. tail.IsSendComplete = true;
  295. }
  296. switch (dType)
  297. {
  298. case DataType.Text:
  299. // string ReceiveInfo = Encoding.UTF8.GetString(recbytes, 0, recbytes.Length);
  300. // AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)>" + ReceiveInfo, sender.ConnectionId, bytes.Length));
  301. if (recBuffer != null)
  302. {
  303. if (!recBuffer.ReceiveComplete(recbytes,tail.IsSendComplete))
  304. {
  305. return HPSocketCS.HandleResult.Error;
  306. }
  307. }
  308. break;
  309. case DataType.File:
  310. if (!sender.ReceiveDownloadFile(header, tail, recBuffer, recbytes))
  311. {
  312. return HPSocketCS.HandleResult.Error;
  313. }
  314. break;
  315. case DataType.Serialization:
  316. case DataType.SQLHelper:
  317. if (recBuffer != null)
  318. {
  319. if (!recBuffer.ReceiveComplete(recbytes, tail.IsSendComplete))
  320. {
  321. return HPSocketCS.HandleResult.Error;
  322. }
  323. }
  324. // break;
  325. break;
  326. case DataType.List:
  327. break;
  328. case DataType.Array:
  329. break;
  330. case DataType.None:
  331. break;
  332. case DataType.PushMessage:
  333. string ReceivePushMessage = Encoding.UTF8.GetString(recbytes, 0, recbytes.Length);
  334. TCP_ProtocolHelperXML Pushhelper = new TCP_ProtocolHelperXML(ReceivePushMessage.Trim());
  335. TCP_FileProtocol Pushprotocol = new TCP_FileProtocol();
  336. Pushprotocol = Pushhelper.GetProtocol();
  337. Pushprotocol.ReceiveFileSize = recbytes.Length;
  338. if (Pushprotocol.Content.Contains("VitalControl"))
  339. {
  340. string recValue = this.SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand.VitalControl, Pushprotocol.Content.Trim(), millisecondsTimeout: 9000);
  341. if (recValue.Trim().Contains("VitalControlOK"))
  342. {
  343. LYFZ.Network.TCPNetworkClient.TCP_NetworkClient.TServerClient.SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand.VitalControlOK, recValue.Trim(), millisecondsTimeout: 9000);
  344. }
  345. }
  346. break;
  347. case DataType.ShowForm:
  348. string ReceiveInfo = Encoding.UTF8.GetString(recbytes, 0, recbytes.Length);
  349. TCP_ProtocolHelperXML helper = new TCP_ProtocolHelperXML(ReceiveInfo.Trim());
  350. TCP_FileProtocol protocol = new TCP_FileProtocol();
  351. protocol = helper.GetProtocol();
  352. protocol.ReceiveFileSize = recbytes.Length;
  353. LYFZ.Network.TCPNetworkServer.EventLockVerified e = new TCPNetworkServer.EventLockVerified();
  354. e.CInfo.IpAddress = header.IPAddress;
  355. e.CInfo.Port =Convert.ToUInt16(header.Port);
  356. e.CInfo.Message = protocol.Content;
  357. if (this.EventClientVerified != null)
  358. {
  359. this.EventClientVerified(e);
  360. }
  361. break;
  362. }
  363. }
  364. }
  365. finally
  366. {
  367. recbytes = null;
  368. }
  369. return HPSocketCS.HandleResult.Ok;
  370. }
  371. catch
  372. {
  373. sender.CCommonLibrary.RemoveServerToClientByteList(header.TransportID);
  374. return HPSocketCS.HandleResult.Ignore;
  375. }
  376. }
  377. catch (Exception ex)
  378. {
  379. SystemFileLogs.WriteLogs("接收数据时出错:" + ex.Message);
  380. return HPSocketCS.HandleResult.Error;
  381. }
  382. finally
  383. {
  384. System.GC.Collect();
  385. }
  386. /* string ReceiveInfo = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
  387. AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)>" + ReceiveInfo, sender.ConnectionId, bytes.Length));
  388. // AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, bytes.Length));
  389. return HandleResult.Ok;*/
  390. }
  391. HPSocketCS.HandleResult OnClose(HPSocketCS.TcpClient sender, HPSocketCS.SocketOperation enOperation, int errorCode)
  392. {
  393. try
  394. {
  395. try
  396. {
  397. sender.CCommonLibrary.ClearAllInvalidResource();
  398. }
  399. catch { }
  400. try
  401. {
  402. sender.CCommonLibrary.ClearAllServerToClientByteList();
  403. }
  404. catch { }
  405. SetAppState(AppState.Stoped);
  406. if (errorCode == 0)
  407. {
  408. // 连接关闭了
  409. // AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));
  410. SystemFileLogs.WriteLogs("连接关闭了");
  411. }
  412. else if (enOperation == HPSocketCS.SocketOperation.Close)
  413. {
  414. SystemFileLogs.WriteLogs(string.Format(" 服务器已关闭连接> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  415. }
  416. else
  417. {
  418. // 出错了
  419. // AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  420. SystemFileLogs.WriteLogs(string.Format(" 连接出错了> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  421. }
  422. // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
  423. // 生产环境请自己控制
  424. // this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
  425. }
  426. catch { }
  427. return HPSocketCS.HandleResult.Ok;
  428. }
  429. /// <summary>
  430. /// 设置程序状态
  431. /// </summary>
  432. /// <param name="state"></param>
  433. void SetAppState(AppState state)
  434. {
  435. appState = state;
  436. }
  437. TCP_RemoteDataHandlerPassiveMode wapper = null;
  438. /// <summary>
  439. ///
  440. /// </summary>
  441. public TCP_RemoteDataHandlerPassiveMode Wapper
  442. {
  443. get { return this.wapper; }
  444. set { this.wapper = value; }
  445. }
  446. /// <summary>
  447. /// 刷新客户端连接
  448. /// </summary>
  449. /// <returns></returns>
  450. public bool RefreshClientList()
  451. {
  452. if (SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand.RefreshClientList).ToLower().Trim() == "ok")
  453. {
  454. return true;
  455. }
  456. else
  457. {
  458. return false;
  459. }
  460. }
  461. /// <summary>
  462. /// 发送信息到客服端并返回服务器的处理结果
  463. /// </summary>
  464. /// <param name="msg"></param>
  465. /// <returns></returns>
  466. public string SendMsgToServer(string msg)
  467. {
  468. return SendCommandToServer(msgOrParameters: msg);
  469. }
  470. static string _FromServerStartTimeStamp = "";
  471. /// <summary>
  472. /// 来自服务器的启动时间标识
  473. /// </summary>
  474. public static string FromServerStartTimeStamp
  475. {
  476. get { return TCP_NetworkClient._FromServerStartTimeStamp; }
  477. set { TCP_NetworkClient._FromServerStartTimeStamp = value; }
  478. }
  479. /// <summary>
  480. /// 发送指令到服务端并返回服务器的处理结果
  481. /// </summary>
  482. /// <param name="command">要发送到服务器的指令</param>
  483. /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
  484. /// <returns></returns>
  485. public string SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello", int millisecondsTimeout = 1000*90)
  486. {
  487. string tempMsg = "";
  488. if (this.appState == AppState.Started)
  489. {
  490. tempMsg = this.Wapper.SendCommandToServerRetMessage(command, msgOrParameters, millisecondsTimeout);
  491. }
  492. return tempMsg;
  493. }
  494. /// <summary>
  495. /// 发送指令到服务端并返回服务器的处理结果
  496. /// </summary>
  497. /// <param name="command">要发送到服务器的指令</param>
  498. /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
  499. /// <returns></returns>
  500. public TCP_FileProtocol SendCommandToServerRetProtocol(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello")
  501. {
  502. TCP_FileProtocol protocol = new TCP_FileProtocol();
  503. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  504. {
  505. protocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, command, msgOrParameters);
  506. }
  507. return protocol;
  508. }
  509. /// <summary>
  510. /// 发送指令到服务端并返回二进制字节数组
  511. /// </summary>
  512. /// <param name="command">要发送到服务器的指令</param>
  513. /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
  514. /// <returns></returns>
  515. public byte[] DataCommandToServerRetByte(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello")
  516. {
  517. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  518. {
  519. TCP_FileProtocol protocol = DataCommandToServerProtocol(command, msgOrParameters);
  520. if (protocol.DataArray != null)
  521. {
  522. return protocol.DataArray;
  523. }
  524. else
  525. {
  526. return null;
  527. }
  528. }
  529. else
  530. {
  531. return null;
  532. }
  533. }
  534. /// <summary>
  535. /// 发送指令到服务端并返回二进制字节数组
  536. /// </summary>
  537. /// <param name="command">要发送到服务器的指令</param>
  538. /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
  539. /// <returns></returns>
  540. public TCP_FileProtocol DataCommandToServerProtocol(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello")
  541. {
  542. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  543. {
  544. return this.Wapper.HP_SendCommandToServer(InformationType.Data, command, msgOrParameters);
  545. }
  546. else
  547. {
  548. return new TCP_FileProtocol();
  549. }
  550. }
  551. /// <summary>
  552. /// 发送SQL指令到服务端并返回结果对象
  553. /// </summary>
  554. /// <param name="requestData"></param>
  555. /// <param name="millisecondsTimeout"></param>
  556. /// <returns></returns>
  557. public HPSocketCS.Extended.SQLHelperReturnData SqlCommandToServerReturnData(HPSocketCS.Extended.SQLHelperRequestData requestData, int millisecondsTimeout = 1000*90)
  558. {
  559. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  560. {
  561. return this.Wapper.HP_SendSqlCommandToServer(requestData, millisecondsTimeout);
  562. }
  563. else
  564. {
  565. return new SQLHelperReturnData("发送SQL指令到服务端时失败,网络连接已断开,请检查网络环境。");
  566. }
  567. }
  568. /// <summary>
  569. /// 上传头像
  570. /// </summary>
  571. /// <param name="fileFullName">要上传的头像路径</param>
  572. /// <param name="backgroundWorker"></param>
  573. /// <returns></returns>
  574. public string UploadAvatarToServer(string fileFullName, BackgroundWorker backgroundWorker = null)
  575. {
  576. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, fileFullName, System.IO.Path.GetFileName(fileFullName), backgroundWorker);
  577. }
  578. /// <summary>
  579. /// 上传文件
  580. /// </summary>
  581. /// <param name="fileFullName">要上传的文件路径</param>
  582. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
  583. /// <param name="backgroundWorker"></param>
  584. /// <returns></returns>
  585. public string UploadFileToServer(string fileFullName, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
  586. {
  587. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, fileFullName, toServerFileFullName, backgroundWorker);
  588. }
  589. /// <summary>
  590. /// 上传图片
  591. /// </summary>
  592. /// <param name="img">要上传的图片</param>
  593. /// <param name="imgFormat">上传的图片格式</param>
  594. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
  595. /// <param name="isDisposeImg">上传后是否释放图片资源</param>
  596. /// <param name="backgroundWorker"></param>
  597. /// <returns></returns>
  598. public string UploadFileToServer(System.Drawing.Image img, System.Drawing.Imaging.ImageFormat imgFormat, string toServerFileFullName, BackgroundWorker backgroundWorker = null, bool isDisposeImg = true)
  599. {
  600. MemoryStream memoryMS = new MemoryStream();
  601. img.Save(memoryMS, imgFormat);
  602. if (isDisposeImg)
  603. {
  604. img.Dispose();
  605. }
  606. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
  607. }
  608. /// <summary>
  609. /// 上传内存流
  610. /// </summary>
  611. /// <param name="memoryMS">要上传的内存流</param>
  612. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
  613. /// <param name="isDisposeImg">上传后是否释放图片资源</param>
  614. /// <param name="backgroundWorker"></param>
  615. /// <returns></returns>
  616. public string UploadFileToServer(MemoryStream memoryMS, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
  617. {
  618. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
  619. }
  620. /// <summary>
  621. /// 获取指定服务器端文件的信息
  622. /// </summary>
  623. /// <param name="sFileName">为你向服务器请求的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  624. /// <returns></returns>
  625. public ServerFileInfo GetServerFileInfo(string sFileName)
  626. {
  627. ServerFileInfo sFileInfo = new ServerFileInfo();
  628. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  629. {
  630. try
  631. {
  632. TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.GetFileInfo, sFileName);
  633. sFileInfo = new ServerFileInfo(sendFileProtocol.Content);
  634. }
  635. catch { sFileInfo.GetMsg = "连接已断开,请检查网络环境是否正常..."; }
  636. }
  637. return sFileInfo;
  638. }
  639. /// <summary>
  640. /// 下载头像
  641. /// </summary>
  642. /// <param name="backgroundWorker"></param>
  643. /// <param name="saveFileFullName">头像下载后保存的位置</param>
  644. /// <param name="fileName">头像图片名(带扩展名)</param>
  645. /// <returns></returns>
  646. public string DownloadAvatar(string saveFileFullName, string fileName, BackgroundWorker backgroundWorker = null)
  647. {
  648. return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, fileName, fileName, backgroundWorker);
  649. }
  650. /// <summary>
  651. /// 下载头像
  652. /// </summary>
  653. /// <param name="backgroundWorker"></param>
  654. /// <param name="memoryMS">保存到指定的内存流中</param>
  655. /// <param name="fileName">头像图片名(带扩展名)</param>
  656. /// <returns></returns>
  657. public string DownloadAvatar(MemoryStream memoryMS, string fileName, BackgroundWorker backgroundWorker = null)
  658. {
  659. return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
  660. }
  661. /// <summary>
  662. /// 下载头像
  663. /// </summary>
  664. /// <param name="resultBitmap">返回下载的图片</param>
  665. /// <param name="fileName">头像图片名(带扩展名)</param>
  666. /// <param name="backgroundWorker"></param>
  667. /// <returns></returns>
  668. public string DownloadAvatar(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
  669. {
  670. try
  671. {
  672. MemoryStream ImageMS = new MemoryStream();
  673. string retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
  674. try
  675. {
  676. resultBitmap = new System.Drawing.Bitmap(ImageMS);
  677. }
  678. catch
  679. {
  680. retMsg = "下载失败,头像生成时失败";
  681. }
  682. ImageMS.Close();
  683. ImageMS.Dispose();
  684. return retMsg;
  685. }
  686. catch (Exception ex)
  687. {
  688. return "下载失败:" + ex.ToString();
  689. }
  690. }
  691. /// <summary>
  692. /// 下载文件
  693. /// </summary>
  694. /// <param name="saveFileFullName">下载后保存的位置</param>
  695. /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  696. /// <param name="backgroundWorker"></param>
  697. /// <returns></returns>
  698. public string DownloadFile(string saveFileFullName, string serverFileFullName, BackgroundWorker backgroundWorker = null)
  699. {
  700. return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, saveFileFullName, serverFileFullName, backgroundWorker);
  701. }
  702. /// <summary>
  703. /// 删除服务上的文件 多个文件用 “|”分隔
  704. /// </summary>
  705. /// <param name="serverFileFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  706. /// <param name="backgroundWorker"></param>
  707. /// <returns></returns>
  708. public string DeleteFile(string serverFileFullName, BackgroundWorker backgroundWorker = null, bool autoMainStoreDownload = true)
  709. {
  710. string ret = "删除失败";
  711. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  712. {
  713. try
  714. {
  715. TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.DeleteFile, serverFileFullName + "?" + autoMainStoreDownload.ToString());
  716. ret = sendFileProtocol.Content;
  717. }
  718. catch { ret = "连接已断开,请检查网络环境是否正常..."; }
  719. }
  720. return ret;
  721. }
  722. /// <summary>
  723. /// 删除服务上的目录
  724. /// </summary>
  725. /// <param name="serverDirectoryFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile”</param>
  726. /// <param name="backgroundWorker"></param>
  727. /// <returns></returns>
  728. public string DeleteDirectory(string serverDirectoryFullName, BackgroundWorker backgroundWorker = null, bool autoMainStoreDownload = true)
  729. {
  730. string ret = "删除失败";
  731. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  732. {
  733. try
  734. {
  735. serverDirectoryFullName = serverDirectoryFullName + "|false|" + autoMainStoreDownload.ToString();
  736. TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.DeleteDirectory, serverDirectoryFullName);
  737. ret = sendFileProtocol.Content;
  738. }
  739. catch { ret = "连接已断开,请检查网络环境是否正常..."; }
  740. }
  741. return ret;
  742. }
  743. /// <summary>
  744. /// 获取服务上的指定目录下的子目录集合
  745. /// </summary>
  746. /// <param name="retDirectoryList">返回的子目录集合</param>
  747. /// <param name="serverDirectoryFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile”</param>
  748. /// <param name="searchPattern">搜索条件</param>
  749. /// <param name="isSearchSubfolder">是否搜索子目录</param>
  750. /// <param name="backgroundWorker"></param>
  751. /// <param name="retDirectoryList">返回的目录集合</param>
  752. /// <returns></returns>
  753. public string GetDirectoryList(out List<string> retDirectoryList, string serverDirectoryFullName, string searchPattern = "*.*", bool isSearchSubfolder = false, BackgroundWorker backgroundWorker = null, bool autoMainStoreDownload = true)
  754. {
  755. string ret = "获取失败";
  756. retDirectoryList = new List<string>();
  757. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  758. {
  759. try
  760. {
  761. serverDirectoryFullName = serverDirectoryFullName + "|" + isSearchSubfolder.ToString() + "|" + searchPattern;
  762. if (!autoMainStoreDownload)
  763. {
  764. serverDirectoryFullName = serverDirectoryFullName + "|" + false.ToString();
  765. }
  766. TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.GetDirectoryList, serverDirectoryFullName);
  767. ret = sendFileProtocol.Content;
  768. if (ret.Contains("成功") && sendFileProtocol.ExtraInfo.Trim().Trim('|').Length > 0)
  769. {
  770. retDirectoryList.AddRange(sendFileProtocol.ExtraInfo.Trim().Trim('|').Split('|'));
  771. }
  772. }
  773. catch { ret = "连接已断开,请检查网络环境是否正常..."; }
  774. }
  775. return ret;
  776. }
  777. /// <summary>
  778. /// 获取服务上的指定目录下的文件集合
  779. /// </summary>
  780. /// <param name="retFileList">返回的文件集合</param>
  781. /// <param name="serverDirectoryFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile”</param>
  782. /// <param name="searchPattern">搜索条件</param>
  783. /// <param name="isSearchSubfolder">是否搜索子目录</param>
  784. /// <param name="backgroundWorker"></param>
  785. /// <param name="autoMainStoreDownload">是否自动连接总店服务器获取总店服务器上的信息</param>
  786. /// <param name="retDirectoryList">返回的目录集合</param>
  787. /// <returns></returns>
  788. public string GetDirectoryFileList(out List<string> retFileList, string serverDirectoryFullName, string searchPattern = "*.*", bool isSearchSubfolder = false, BackgroundWorker backgroundWorker = null, int millisecondsTimeout = 1000*90, bool autoMainStoreDownload = true)
  789. {
  790. string ret = "获取失败";
  791. retFileList = new List<string>();
  792. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  793. {
  794. try
  795. {
  796. serverDirectoryFullName = serverDirectoryFullName + "|" + isSearchSubfolder.ToString() + "|" + searchPattern;
  797. if (!autoMainStoreDownload) {
  798. serverDirectoryFullName = serverDirectoryFullName + "|"+false.ToString();
  799. }
  800. TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.GeTFileList, serverDirectoryFullName, millisecondsTimeout);
  801. ret = sendFileProtocol.Content;
  802. if (ret.Contains("成功") && sendFileProtocol.ExtraInfo.Trim().Trim('|').Length > 0)
  803. {
  804. retFileList.AddRange(sendFileProtocol.ExtraInfo.Trim().Trim('|').Split('|'));
  805. }
  806. }
  807. catch { ret = "连接已断开,请检查网络环境是否正常..."; }
  808. }
  809. return ret;
  810. }
  811. /// <summary>
  812. /// 下载文件
  813. /// </summary>
  814. /// <param name="memoryMS">保存到指定的内存流中</param>
  815. /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  816. /// <param name="backgroundWorker"></param>
  817. /// <returns></returns>
  818. public string DownloadFile(MemoryStream memoryMS, string serverFileFullName, BackgroundWorker backgroundWorker = null)
  819. {
  820. return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", serverFileFullName, backgroundWorker);
  821. }
  822. /// <summary>
  823. /// 下载图像
  824. /// </summary>
  825. /// <param name="backgroundWorker"></param>
  826. /// <param name="resultBitmap">返回下载的图片</param>
  827. /// <param name="fileName">要下载的图片路径,以服务器程序的根目录定位 如“UpdateTemp\\test.jpg”</param>
  828. /// <returns></returns>
  829. public string DownloadBitmap(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
  830. {
  831. try
  832. {
  833. string retMsg = "";
  834. if (LYFZ.WinAPI.CustomPublicMethod.ExistsImgage(fileName))
  835. {
  836. MemoryStream ImageMS = new MemoryStream();
  837. retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", fileName, backgroundWorker);
  838. if (retMsg.Contains("成功"))
  839. {
  840. try
  841. {
  842. resultBitmap = new System.Drawing.Bitmap(ImageMS);
  843. }
  844. catch
  845. {
  846. retMsg = "下载失败,图像生成失败";
  847. }
  848. }
  849. else
  850. {
  851. if (retMsg.Trim() == "")
  852. {
  853. retMsg = "下载失败,请重试";
  854. }
  855. }
  856. ImageMS.Close();
  857. ImageMS.Dispose();
  858. }
  859. else
  860. {
  861. retMsg = "您请求下载的文件不是图片,不能下载";
  862. }
  863. return retMsg;
  864. }
  865. catch (Exception ex)
  866. {
  867. return "下载失败:" + ex.ToString();
  868. }
  869. }
  870. /// <summary>
  871. /// 向服务器上传文件
  872. /// </summary>
  873. /// <param name="command">上传命令</param>
  874. /// <param name="fileFullName">上传的文件全路径</param>
  875. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  876. /// <param name="backgroundWorker">参数</param>
  877. /// <param name="memoryMS"></param>
  878. /// <param name="autoMainStoreDownload">如果是分店是否自动上传文件到总店服务器</param>
  879. /// <returns></returns>
  880. public string SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, string fileFullName = "", string toServerFileFullName = "", BackgroundWorker backgroundWorker = null, MemoryStream memoryMS = null)
  881. {
  882. string tempMsg = "";
  883. string fileName = toServerFileFullName;
  884. bool ret = false;
  885. TCP_NetworkClient myUploadClient = this.TFileClient;
  886. if (this.TFileClient.AppState != HPSocketCS.Extended.AppState.Started)
  887. {
  888. this.TFileClient.ConnectionServer();
  889. }
  890. if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
  891. {
  892. //如果是上传头像时设置头像路径
  893. toServerFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(toServerFileFullName);
  894. }
  895. if (myUploadClient.AppState == HPSocketCS.Extended.AppState.Started)
  896. {
  897. ServerFileInfo downloadFileInfo = myUploadClient.GetServerFileInfo(toServerFileFullName);
  898. bool isUpload = true;//是否需要上传文件 用于判断要上传的文件是否在服务器上存在,如果存在就不上传
  899. if (downloadFileInfo.IsExists)
  900. {
  901. if (downloadFileInfo.FileMd5.Trim().Length > 0)
  902. {
  903. if (memoryMS == null && fileFullName.Trim().Length > 0)
  904. {
  905. if (System.IO.File.Exists(fileFullName.Trim()))
  906. {
  907. FileInfo fi = new FileInfo(fileFullName.Trim());
  908. if (fi.Length < HPSocketCS.Sdk.FileMD5VerifySize)
  909. {
  910. string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(fileFullName.Trim());
  911. if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
  912. {
  913. isUpload = false;
  914. }
  915. }
  916. }
  917. }
  918. else if (memoryMS != null)
  919. {
  920. if (downloadFileInfo.FileMd5.Trim().Length > 0)
  921. {
  922. memoryMS.Position = 0;
  923. byte[] bytes = new byte[memoryMS.Length];
  924. memoryMS.Read(bytes, 0, bytes.Length);
  925. string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(bytes);
  926. Array.Clear(bytes, 0, bytes.Length);
  927. bytes = null;
  928. if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
  929. {
  930. isUpload = false;
  931. }
  932. }
  933. }
  934. }
  935. }
  936. if (isUpload)
  937. {
  938. if (fileFullName.Trim().Length > 0 && System.IO.File.Exists(fileFullName.Trim()) && memoryMS == null)
  939. {
  940. ret = myUploadClient.Client.UploadFiles(fileFullName.Trim(), toServerFileFullName, backgroundWorker);
  941. }
  942. else if (memoryMS != null)
  943. {
  944. ret = myUploadClient.Client.UploadMemoryStream(memoryMS, toServerFileFullName, backgroundWorker);
  945. }
  946. else
  947. {
  948. return "要上传的文件不存在:" + fileFullName;
  949. }
  950. }
  951. else
  952. {
  953. ret = true;
  954. }
  955. }
  956. else
  957. {
  958. return "网络连接失败,请检查网络环境";
  959. }
  960. if (ret)
  961. {
  962. tempMsg = "上传成功";
  963. }
  964. else
  965. {
  966. tempMsg = "上传失败";
  967. }
  968. return tempMsg;
  969. }
  970. /// <summary>
  971. /// 临时缓存文件目录
  972. /// </summary>
  973. static string TemporaryCachefilesPath = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + "Temp\\TemporaryCachefiles\\";
  974. // static bool isFileServerIng = false;
  975. /// <summary>
  976. /// 从服务器下载文件
  977. /// </summary>
  978. /// <param name="memoryMS"></param>
  979. /// <param name="command">下载命令</param>
  980. /// <param name="saveFileFullName">下载后要保存的文件全路</param>
  981. /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  982. /// <param name="backgroundWorker"></param>
  983. /// <param name="requestNumber">请求下载的次数 用于在下载失败时判断是否自动重新请求下载</param>
  984. /// <param name="autoMainStoreDownload">如果是分店是否自动到总店服务器下载文件</param>
  985. /// <returns></returns>
  986. public string ReceiveFileCommandToServer(MemoryStream memoryMS = null, HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, string saveFileFullName = "", string serverFileFullName = "", BackgroundWorker backgroundWorker = null)
  987. {
  988. string tempMsg = "";
  989. // if (!isFileServerIng)
  990. {
  991. try
  992. {
  993. bool ret = false;
  994. TCP_NetworkClient myDownLoadClient = this.TFileClient;
  995. if (myDownLoadClient.AppState != HPSocketCS.Extended.AppState.Started)
  996. {
  997. myDownLoadClient.ConnectionServer();
  998. }
  999. if (myDownLoadClient.AppState == HPSocketCS.Extended.AppState.Started)
  1000. {
  1001. if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
  1002. {
  1003. //如果是下载头像时设置头像在服务器上的路径
  1004. serverFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(serverFileFullName);
  1005. }
  1006. ServerFileInfo downloadFileInfo = myDownLoadClient.GetServerFileInfo(serverFileFullName);
  1007. if (downloadFileInfo.IsExists)
  1008. {
  1009. if (memoryMS == null && saveFileFullName.Trim().Length > 0)
  1010. {
  1011. if (downloadFileInfo.FileSize < HPSocketCS.Sdk.FileMD5VerifySize && downloadFileInfo.FileMd5.Trim().Length > 0 && System.IO.File.Exists(saveFileFullName.Trim()))
  1012. {
  1013. string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(saveFileFullName.Trim());
  1014. if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
  1015. {
  1016. ret = true;
  1017. }
  1018. else
  1019. {
  1020. ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
  1021. }
  1022. }
  1023. else
  1024. {
  1025. ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
  1026. }
  1027. }
  1028. else if (memoryMS != null)
  1029. {
  1030. string TempCachefilePath = TemporaryCachefilesPath + downloadFileInfo.FileMd5 + "_" + System.IO.Path.GetFileName(serverFileFullName);
  1031. byte[] TempCachefileBytes = null;
  1032. bool TempCachefileExists = false;
  1033. try
  1034. {
  1035. if (System.IO.File.Exists(TempCachefilePath))
  1036. {
  1037. TempCachefileBytes= System.IO.File.ReadAllBytes(TempCachefilePath);
  1038. TempCachefileExists = true;
  1039. }
  1040. }
  1041. catch { }
  1042. if (!TempCachefileExists)
  1043. {
  1044. MemoryStream recMemoryMS = myDownLoadClient.Client.DownloadMemoryStream(serverFileFullName, backgroundWorker);
  1045. if (recMemoryMS != null)
  1046. {
  1047. try
  1048. {
  1049. if (!System.IO.Directory.Exists(TemporaryCachefilesPath))
  1050. {
  1051. System.IO.Directory.CreateDirectory(TemporaryCachefilesPath);
  1052. }
  1053. recMemoryMS.Position = 0;
  1054. byte[] bytes = new byte[recMemoryMS.Length];
  1055. recMemoryMS.Read(bytes, 0, bytes.Length);
  1056. System.IO.File.WriteAllBytes(TempCachefilePath, bytes);
  1057. Array.Clear(bytes, 0, bytes.Length);
  1058. bytes = null;
  1059. }
  1060. catch { }
  1061. recMemoryMS.WriteTo(memoryMS);
  1062. memoryMS.Position = 0;
  1063. recMemoryMS.Close();
  1064. recMemoryMS.Dispose();
  1065. recMemoryMS = null;
  1066. ret = true;
  1067. }
  1068. }
  1069. else {
  1070. memoryMS.Write(TempCachefileBytes, 0, TempCachefileBytes.Length);
  1071. System.Array.Clear(TempCachefileBytes, 0, TempCachefileBytes.Length);
  1072. TempCachefileBytes = null;
  1073. ret = true;
  1074. }
  1075. }
  1076. else
  1077. {
  1078. return "下载请求错误";
  1079. }
  1080. }
  1081. else
  1082. {
  1083. return downloadFileInfo.GetMsg;
  1084. }
  1085. }
  1086. else
  1087. {
  1088. return "网络连接失败,请检查网络环境";
  1089. }
  1090. if (ret)
  1091. {
  1092. tempMsg = "下载成功";
  1093. }
  1094. else
  1095. {
  1096. tempMsg = "下载失败";
  1097. }
  1098. }
  1099. catch (Exception ex)
  1100. {
  1101. tempMsg = "下载出错:" + ex.Message;
  1102. }
  1103. // finally
  1104. // {
  1105. // isFileServerIng = false;
  1106. // }
  1107. }
  1108. return tempMsg;
  1109. }
  1110. static TCP_NetworkClient tServerClient = null;
  1111. public static TCP_NetworkClient TServerClient
  1112. {
  1113. get
  1114. {
  1115. if (TCP_NetworkClient.tServerClient == null)
  1116. {
  1117. TCP_NetworkClient.tServerClient = new TCP_NetworkClient();
  1118. }
  1119. return TCP_NetworkClient.tServerClient;
  1120. }
  1121. }
  1122. #endregion
  1123. }
  1124. }