TCP_NetworkClient.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 System.ComponentModel;
  9. using HPSocketCS.Extended;
  10. using System.Runtime.InteropServices;
  11. namespace HPNetwork.TCPNetworkClient
  12. {
  13. /// <summary>
  14. /// TCP网络通信客户端
  15. /// </summary>
  16. public class TCP_NetworkClient
  17. {
  18. public TCP_NetworkClient() {
  19. }
  20. #region 网络客户端程序处理代码
  21. TCP_NetworkClient tFileClient=null;
  22. /// <summary>
  23. /// 文件传送通道
  24. /// </summary>
  25. public TCP_NetworkClient TFileClient
  26. {
  27. get {
  28. if (this.tFileClient == null)
  29. {
  30. this.tFileClient = new TCP_NetworkClient();
  31. }
  32. return this.tFileClient;
  33. }
  34. }
  35. private AppState appState = AppState.Stoped;
  36. /// <summary>
  37. /// 当前网络状态
  38. /// </summary>
  39. public AppState AppState
  40. {
  41. get { return appState; }
  42. set { appState = value; }
  43. }
  44. // private delegate void ConnectUpdateUiDelegate();
  45. // private delegate void SetAppStateDelegate(AppState state);
  46. HPSocketCS.TcpPackClient client = new HPSocketCS.TcpPackClient();
  47. /// <summary>
  48. /// 客户端连接
  49. /// </summary>
  50. public HPSocketCS.TcpPackClient Client
  51. {
  52. get { return client; }
  53. }
  54. /// <summary>
  55. /// 连接服务器
  56. /// </summary>
  57. /// <param name="ip">ip</param>
  58. /// <param name="port">端口</param>
  59. /// <param name="isAsyncConn">是否异步连接</param>
  60. /// <returns></returns>
  61. public bool ConnectionServer(string hostOrIP="", ushort port=0, bool isAsyncConn = false)
  62. {
  63. try
  64. {
  65. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  66. {
  67. return true;
  68. }
  69. if (!this.isInitializesNetwork)
  70. {
  71. this.InitializesNetwork();
  72. }
  73. bool cAsyncConn = isAsyncConn;
  74. // 写在这个位置是上面可能会异常
  75. SetAppState(AppState.Starting);
  76. // AddMsg(string.Format("$Client Starting ... -> ({0}:{1})", ip, port));
  77. SystemFileLogs.WriteLogs(string.Format("客户端开始连接... -> ({0}:{1})", hostOrIP, port));
  78. if (client.Connetion(hostOrIP, port, cAsyncConn))
  79. {
  80. if (cAsyncConn == false)
  81. {
  82. SetAppState(AppState.Started);
  83. }
  84. // AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
  85. SystemFileLogs.WriteLogs(string.Format("客户端连接OK -> ({0}:{1})", hostOrIP, port));
  86. return true;
  87. }
  88. else
  89. {
  90. SetAppState(AppState.Stoped);
  91. throw new Exception(string.Format("客户端连接出错 -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  92. }
  93. }
  94. catch (Exception ex)
  95. {
  96. SystemFileLogs.WriteLogs(string.Format("客户端连接失败-> ({0})", ex.Message));
  97. }
  98. return false;
  99. }
  100. /// <summary>
  101. /// 关闭客户端连接
  102. /// </summary>
  103. /// <returns></returns>
  104. public bool CloseConnected()
  105. {
  106. // 停止服务
  107. SystemFileLogs.WriteLogs(string.Format("准备关闭客户端连接"));
  108. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  109. {
  110. if (client.Stop())
  111. {
  112. SetAppState(AppState.Stoped);
  113. if (this.tFileClient != null && this.tFileClient.AppState == HPSocketCS.Extended.AppState.Started)
  114. {
  115. this.tFileClient.CloseConnected();
  116. }
  117. return true;
  118. }
  119. else
  120. {
  121. // AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
  122. SystemFileLogs.WriteLogs(string.Format("关闭客户端连接失败-> {0}({1})", client.ErrorMessage, client.ErrorCode));
  123. }
  124. }
  125. else {
  126. return true;
  127. }
  128. return false;
  129. }
  130. bool isInitializesNetwork = false;
  131. /// <summary>
  132. /// 网络服务是否已初始化
  133. /// </summary>
  134. public bool IsInitializesNetwork
  135. {
  136. get { return isInitializesNetwork; }
  137. set { isInitializesNetwork = value; }
  138. }
  139. /// <summary>
  140. /// 初始化网络
  141. /// </summary>
  142. void InitializesNetwork()
  143. {
  144. try
  145. {
  146. // 设置client事件
  147. client.OnPrepareConnect += new HPSocketCS.TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
  148. client.OnConnect += new HPSocketCS.TcpClientEvent.OnConnectEventHandler(OnConnect);
  149. client.OnSend += new HPSocketCS.TcpClientEvent.OnSendEventHandler(OnSend);
  150. client.OnReceive += new HPSocketCS.TcpClientEvent.OnReceiveEventHandler(OnReceive);
  151. client.OnClose += new HPSocketCS.TcpClientEvent.OnCloseEventHandler(OnClose);
  152. // 设置包头标识,与对端设置保证一致性
  153. client.PackHeaderFlag = 0x1ff;
  154. // 设置最大封包大小
  155. client.MaxPackSize = 0x2000 * 32;
  156. client.SocketBufferSize = 512 * 1024;//client.MaxPackSize;
  157. SystemFileLogs.WriteLogs("客户初始化网络成功");
  158. SetAppState(AppState.Stoped);
  159. this.isInitializesNetwork = true;
  160. }
  161. catch (Exception ex)
  162. {
  163. SetAppState(AppState.Error);
  164. // AddMsg(ex.Message);
  165. SystemFileLogs.WriteLogs("客户初始化网络时出错:" + ex.Message);
  166. }
  167. }
  168. HPSocketCS.HandleResult OnPrepareConnect(HPSocketCS.TcpClient sender, uint socket)
  169. {
  170. return HPSocketCS.HandleResult.Ok;
  171. }
  172. HPSocketCS.HandleResult OnConnect(HPSocketCS.TcpClient sender)
  173. {
  174. // 已连接 到达一次
  175. // 设置附加数据
  176. string ip = "";
  177. ushort port = 0;
  178. if (sender.GetListenAddress(ref ip, ref port))
  179. {
  180. HPSocketCS.Extended.ClientInfo ci = new HPSocketCS.Extended.ClientInfo();
  181. ci.ConnId = sender.ConnectionId;
  182. ci.IpAddress = ip;
  183. ci.Port = port;
  184. sender.SetExtra(ci);
  185. }
  186. // 如果是异步联接,更新界面状态
  187. // this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));
  188. // AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));
  189. SystemFileLogs.WriteLogs("已连接:" + ip + ":" + port.ToString());
  190. return HPSocketCS.HandleResult.Ok;
  191. }
  192. HPSocketCS.HandleResult OnSend(HPSocketCS.TcpClient sender, byte[] bytes)
  193. {
  194. // 客户端发数据了
  195. //AddMsg(string.Format(" > [{0},OnSend] ->数据发送成功 ({1} bytes)", sender.ConnectionId, bytes.Length));
  196. return HPSocketCS.HandleResult.Ok;
  197. }
  198. HPSocketCS.HandleResult OnReceive(HPSocketCS.TcpClient sender, byte[] bytes)
  199. {
  200. // 数据到达了
  201. try
  202. {
  203. //收到的数据
  204. byte[] receiveBytes = new byte[0];
  205. TcpHeadInfo header = sender.BytesToStruct<TcpHeadInfo>(bytes);
  206. try
  207. {
  208. DataType dType = (DataType)header.MsgDataType;
  209. int headSize = Marshal.SizeOf(header);
  210. TcpTailInfo tail = new TcpTailInfo();
  211. if (header.IsTail)
  212. {
  213. //有附加尾数据时
  214. int tailSize = Marshal.SizeOf(tail);
  215. byte[] tailBytes = new byte[tailSize];
  216. Array.ConstrainedCopy(bytes, bytes.Length - tailSize, tailBytes, 0, tailBytes.Length);
  217. tail = sender.BytesToStruct<TcpTailInfo>(tailBytes);
  218. receiveBytes = new byte[bytes.Length - headSize - tailSize];
  219. Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
  220. tailBytes = null;
  221. }
  222. else
  223. {
  224. // 因为没有附加尾数据,所以大小可以用length - objSize
  225. receiveBytes = new byte[bytes.Length - headSize];
  226. Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
  227. }
  228. ReceiveCacheBuffer recBuffer = sender.CCommonLibrary.GetReceiveCacheBuffer(header.TransportID);
  229. if (recBuffer != null)
  230. {
  231. lock (recBuffer)
  232. {
  233. recBuffer.Length += receiveBytes.Length;
  234. if (recBuffer.BackgroundWorker != null)
  235. {
  236. //总计数器
  237. long sumCount = header.IntactSize;
  238. if (dType == DataType.File)
  239. {
  240. sumCount = tail.FileSize;
  241. }
  242. //当前计数器
  243. long currentCount = recBuffer.Length;
  244. if (header.TransportEnd && tail.IsSendComplete)
  245. {
  246. currentCount = Convert.ToInt64(sumCount);
  247. }
  248. CommonLibrary.SetBackgroundWorker(sumCount, currentCount,"正在接收数据,请稍等...", recBuffer.BackgroundWorker);
  249. }
  250. }
  251. }
  252. //接收到的客户端发送来的数据
  253. byte[] recbytes = null;
  254. try
  255. {
  256. if (header.TransportStart && header.TransportEnd)
  257. {
  258. recbytes = receiveBytes;
  259. receiveBytes = null;
  260. }
  261. else
  262. {
  263. ReceiveData rData = sender.CCommonLibrary.GetReceiveData(header);
  264. if (rData == null)
  265. {
  266. rData = new ReceiveData();
  267. sender.CCommonLibrary.AddReceiveData(rData);
  268. }
  269. rData.ReceiveRemoteClientInfo = header;
  270. rData.ReceiveDataMstream.Write(receiveBytes, 0, receiveBytes.Length);
  271. if (header.TransportEnd)
  272. {
  273. recbytes = rData.ReceiveDataMstream.ToArray();
  274. sender.CCommonLibrary.RemoveReceiveDataData(rData);
  275. }
  276. }
  277. if (recbytes != null)
  278. {
  279. recbytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(recbytes);
  280. if (!header.IsTail && header.TransportEnd)
  281. {
  282. tail.IsSendComplete = true;
  283. }
  284. switch (dType)
  285. {
  286. case DataType.Text:
  287. if (recBuffer != null)
  288. {
  289. if (!recBuffer.ReceiveComplete(recbytes,tail.IsSendComplete))
  290. {
  291. return HPSocketCS.HandleResult.Error;
  292. }
  293. }
  294. break;
  295. case DataType.File:
  296. if (!sender.ReceiveDownloadFile(header, tail, recBuffer, recbytes))
  297. {
  298. return HPSocketCS.HandleResult.Error;
  299. }
  300. break;
  301. case DataType.Serialization:
  302. case DataType.SQLHelper:
  303. if (recBuffer != null)
  304. {
  305. if (!recBuffer.ReceiveComplete(recbytes, tail.IsSendComplete))
  306. {
  307. return HPSocketCS.HandleResult.Error;
  308. }
  309. }
  310. // break;
  311. break;
  312. case DataType.List:
  313. break;
  314. case DataType.Array:
  315. break;
  316. case DataType.None:
  317. break;
  318. }
  319. }
  320. }
  321. finally
  322. {
  323. recbytes = null;
  324. }
  325. return HPSocketCS.HandleResult.Ok;
  326. }
  327. catch
  328. {
  329. sender.CCommonLibrary.RemoveServerToClientByteList(header.TransportID);
  330. return HPSocketCS.HandleResult.Ignore;
  331. }
  332. }
  333. catch (Exception ex)
  334. {
  335. SystemFileLogs.WriteLogs("接收数据时出错:" + ex.Message);
  336. return HPSocketCS.HandleResult.Error;
  337. }
  338. finally
  339. {
  340. System.GC.Collect();
  341. }
  342. }
  343. HPSocketCS.HandleResult OnClose(HPSocketCS.TcpClient sender, HPSocketCS.SocketOperation enOperation, int errorCode)
  344. {
  345. try
  346. {
  347. try
  348. {
  349. sender.CCommonLibrary.ClearAllInvalidResource();
  350. }
  351. catch { }
  352. try
  353. {
  354. sender.CCommonLibrary.ClearAllServerToClientByteList();
  355. }
  356. catch { }
  357. SetAppState(AppState.Stoped);
  358. if (errorCode == 0)
  359. {
  360. // 连接关闭了
  361. // AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));
  362. SystemFileLogs.WriteLogs("连接关闭了");
  363. }
  364. else if (enOperation == HPSocketCS.SocketOperation.Close)
  365. {
  366. SystemFileLogs.WriteLogs(string.Format(" 服务器已关闭连接> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  367. }
  368. else
  369. {
  370. // 出错了
  371. // AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  372. SystemFileLogs.WriteLogs(string.Format(" 连接出错了> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
  373. }
  374. // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
  375. // 生产环境请自己控制
  376. // this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
  377. }
  378. catch { }
  379. return HPSocketCS.HandleResult.Ok;
  380. }
  381. /// <summary>
  382. /// 设置程序状态
  383. /// </summary>
  384. /// <param name="state"></param>
  385. void SetAppState(AppState state)
  386. {
  387. appState = state;
  388. }
  389. /// <summary>
  390. /// 上传头像
  391. /// </summary>
  392. /// <param name="fileFullName">要上传的头像路径</param>
  393. /// <param name="backgroundWorker"></param>
  394. /// <returns></returns>
  395. public string UploadAvatarToServer(string fileFullName, BackgroundWorker backgroundWorker = null)
  396. {
  397. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, fileFullName, System.IO.Path.GetFileName(fileFullName), backgroundWorker);
  398. }
  399. /// <summary>
  400. /// 上传文件
  401. /// </summary>
  402. /// <param name="fileFullName">要上传的文件路径</param>
  403. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
  404. /// <param name="backgroundWorker"></param>
  405. /// <returns></returns>
  406. public string UploadFileToServer(string fileFullName, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
  407. {
  408. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, fileFullName, toServerFileFullName, backgroundWorker);
  409. }
  410. /// <summary>
  411. /// 上传图片
  412. /// </summary>
  413. /// <param name="img">要上传的图片</param>
  414. /// <param name="imgFormat">上传的图片格式</param>
  415. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
  416. /// <param name="isDisposeImg">上传后是否释放图片资源</param>
  417. /// <param name="backgroundWorker"></param>
  418. /// <returns></returns>
  419. public string UploadFileToServer(System.Drawing.Image img, System.Drawing.Imaging.ImageFormat imgFormat, string toServerFileFullName, BackgroundWorker backgroundWorker = null, bool isDisposeImg = true)
  420. {
  421. MemoryStream memoryMS = new MemoryStream();
  422. img.Save(memoryMS, imgFormat);
  423. if (isDisposeImg)
  424. {
  425. img.Dispose();
  426. }
  427. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
  428. }
  429. /// <summary>
  430. /// 上传内存流
  431. /// </summary>
  432. /// <param name="memoryMS">要上传的内存流</param>
  433. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
  434. /// <param name="isDisposeImg">上传后是否释放图片资源</param>
  435. /// <param name="backgroundWorker"></param>
  436. /// <returns></returns>
  437. public string UploadFileToServer(MemoryStream memoryMS, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
  438. {
  439. return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
  440. }
  441. /// <summary>
  442. /// 获取指定服务器端文件的信息
  443. /// </summary>
  444. /// <param name="sFileName">为你向服务器请求的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  445. /// <returns></returns>
  446. public ServerFileInfo GetServerFileInfo(string sFileName)
  447. {
  448. ServerFileInfo sFileInfo = new ServerFileInfo();
  449. if (this.AppState == HPSocketCS.Extended.AppState.Started)
  450. {
  451. try
  452. {
  453. // sFileInfo = new ServerFileInfo(sendFileProtocol.Content);
  454. }
  455. catch { sFileInfo.GetMsg = "连接已断开,请检查网络环境是否正常..."; }
  456. }
  457. return sFileInfo;
  458. }
  459. /// <summary>
  460. /// 下载头像
  461. /// </summary>
  462. /// <param name="backgroundWorker"></param>
  463. /// <param name="saveFileFullName">头像下载后保存的位置</param>
  464. /// <param name="fileName">头像图片名(带扩展名)</param>
  465. /// <returns></returns>
  466. public string DownloadAvatar(string saveFileFullName, string fileName, BackgroundWorker backgroundWorker = null)
  467. {
  468. return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, fileName, fileName, backgroundWorker);
  469. }
  470. /// <summary>
  471. /// 下载头像
  472. /// </summary>
  473. /// <param name="backgroundWorker"></param>
  474. /// <param name="memoryMS">保存到指定的内存流中</param>
  475. /// <param name="fileName">头像图片名(带扩展名)</param>
  476. /// <returns></returns>
  477. public string DownloadAvatar(MemoryStream memoryMS, string fileName, BackgroundWorker backgroundWorker = null)
  478. {
  479. return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
  480. }
  481. /// <summary>
  482. /// 下载头像
  483. /// </summary>
  484. /// <param name="resultBitmap">返回下载的图片</param>
  485. /// <param name="fileName">头像图片名(带扩展名)</param>
  486. /// <param name="backgroundWorker"></param>
  487. /// <returns></returns>
  488. public string DownloadAvatar(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
  489. {
  490. try
  491. {
  492. MemoryStream ImageMS = new MemoryStream();
  493. string retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
  494. try
  495. {
  496. resultBitmap = new System.Drawing.Bitmap(ImageMS);
  497. }
  498. catch
  499. {
  500. retMsg = "下载失败,头像生成时失败";
  501. }
  502. ImageMS.Close();
  503. ImageMS.Dispose();
  504. return retMsg;
  505. }
  506. catch (Exception ex)
  507. {
  508. return "下载失败:" + ex.ToString();
  509. }
  510. }
  511. /// <summary>
  512. /// 下载文件
  513. /// </summary>
  514. /// <param name="saveFileFullName">下载后保存的位置</param>
  515. /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  516. /// <param name="backgroundWorker"></param>
  517. /// <returns></returns>
  518. public string DownloadFile(string saveFileFullName, string serverFileFullName, BackgroundWorker backgroundWorker = null)
  519. {
  520. return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, saveFileFullName, serverFileFullName, backgroundWorker);
  521. }
  522. /// <summary>
  523. /// 下载文件
  524. /// </summary>
  525. /// <param name="memoryMS">保存到指定的内存流中</param>
  526. /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  527. /// <param name="backgroundWorker"></param>
  528. /// <returns></returns>
  529. public string DownloadFile(MemoryStream memoryMS, string serverFileFullName, BackgroundWorker backgroundWorker = null)
  530. {
  531. return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", serverFileFullName, backgroundWorker);
  532. }
  533. /// <summary>
  534. /// 下载图像
  535. /// </summary>
  536. /// <param name="backgroundWorker"></param>
  537. /// <param name="resultBitmap">返回下载的图片</param>
  538. /// <param name="fileName">要下载的图片路径,以服务器程序的根目录定位 如“UpdateTemp\\test.jpg”</param>
  539. /// <returns></returns>
  540. public string DownloadBitmap(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
  541. {
  542. try
  543. {
  544. string retMsg = "";
  545. if (LYFZ.WinAPI.CustomPublicMethod.ExistsImgage(fileName))
  546. {
  547. MemoryStream ImageMS = new MemoryStream();
  548. retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", fileName, backgroundWorker);
  549. if (retMsg.Contains("成功"))
  550. {
  551. try
  552. {
  553. resultBitmap = new System.Drawing.Bitmap(ImageMS);
  554. }
  555. catch
  556. {
  557. retMsg = "下载失败,图像生成失败";
  558. }
  559. }
  560. else
  561. {
  562. if (retMsg.Trim() == "")
  563. {
  564. retMsg = "下载失败,请重试";
  565. }
  566. }
  567. ImageMS.Close();
  568. ImageMS.Dispose();
  569. }
  570. else
  571. {
  572. retMsg = "您请求下载的文件不是图片,不能下载";
  573. }
  574. return retMsg;
  575. }
  576. catch (Exception ex)
  577. {
  578. return "下载失败:" + ex.ToString();
  579. }
  580. }
  581. /// <summary>
  582. /// 向服务器上传文件
  583. /// </summary>
  584. /// <param name="command">上传命令</param>
  585. /// <param name="fileFullName">上传的文件全路径</param>
  586. /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  587. /// <param name="backgroundWorker">参数</param>
  588. /// <param name="memoryMS"></param>
  589. /// <param name="autoMainStoreDownload">如果是分店是否自动上传文件到总店服务器</param>
  590. /// <returns></returns>
  591. public string SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, string fileFullName = "", string toServerFileFullName = "", BackgroundWorker backgroundWorker = null, MemoryStream memoryMS = null)
  592. {
  593. string tempMsg = "";
  594. string fileName = toServerFileFullName;
  595. bool ret = false;
  596. TCP_NetworkClient myUploadClient = this.TFileClient;
  597. if (this.TFileClient.AppState != HPSocketCS.Extended.AppState.Started)
  598. {
  599. this.TFileClient.ConnectionServer();
  600. }
  601. if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
  602. {
  603. //如果是上传头像时设置头像路径
  604. toServerFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(toServerFileFullName);
  605. }
  606. if (myUploadClient.AppState == HPSocketCS.Extended.AppState.Started)
  607. {
  608. ServerFileInfo downloadFileInfo = myUploadClient.GetServerFileInfo(toServerFileFullName);
  609. bool isUpload = true;//是否需要上传文件 用于判断要上传的文件是否在服务器上存在,如果存在就不上传
  610. if (downloadFileInfo.IsExists)
  611. {
  612. if (downloadFileInfo.FileMd5.Trim().Length > 0)
  613. {
  614. if (memoryMS == null && fileFullName.Trim().Length > 0)
  615. {
  616. if (System.IO.File.Exists(fileFullName.Trim()))
  617. {
  618. FileInfo fi = new FileInfo(fileFullName.Trim());
  619. if (fi.Length < HPSocketCS.Sdk.FileMD5VerifySize)
  620. {
  621. string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(fileFullName.Trim());
  622. if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
  623. {
  624. isUpload = false;
  625. }
  626. }
  627. }
  628. }
  629. else if (memoryMS != null)
  630. {
  631. if (downloadFileInfo.FileMd5.Trim().Length > 0)
  632. {
  633. memoryMS.Position = 0;
  634. byte[] bytes = new byte[memoryMS.Length];
  635. memoryMS.Read(bytes, 0, bytes.Length);
  636. string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(bytes);
  637. Array.Clear(bytes, 0, bytes.Length);
  638. bytes = null;
  639. if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
  640. {
  641. isUpload = false;
  642. }
  643. }
  644. }
  645. }
  646. }
  647. if (isUpload)
  648. {
  649. if (fileFullName.Trim().Length > 0 && System.IO.File.Exists(fileFullName.Trim()) && memoryMS == null)
  650. {
  651. ret = myUploadClient.Client.UploadFiles(fileFullName.Trim(), toServerFileFullName, backgroundWorker);
  652. }
  653. else if (memoryMS != null)
  654. {
  655. ret = myUploadClient.Client.UploadMemoryStream(memoryMS, toServerFileFullName, backgroundWorker);
  656. }
  657. else
  658. {
  659. return "要上传的文件不存在:" + fileFullName;
  660. }
  661. }
  662. else
  663. {
  664. ret = true;
  665. }
  666. }
  667. else
  668. {
  669. return "网络连接失败,请检查网络环境";
  670. }
  671. if (ret)
  672. {
  673. tempMsg = "上传成功";
  674. }
  675. else
  676. {
  677. tempMsg = "上传失败";
  678. }
  679. return tempMsg;
  680. }
  681. /// <summary>
  682. /// 临时缓存文件目录
  683. /// </summary>
  684. static string TemporaryCachefilesPath = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + "Temp\\TemporaryCachefiles\\";
  685. // static bool isFileServerIng = false;
  686. /// <summary>
  687. /// 从服务器下载文件
  688. /// </summary>
  689. /// <param name="memoryMS"></param>
  690. /// <param name="command">下载命令</param>
  691. /// <param name="saveFileFullName">下载后要保存的文件全路</param>
  692. /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
  693. /// <param name="backgroundWorker"></param>
  694. /// <param name="requestNumber">请求下载的次数 用于在下载失败时判断是否自动重新请求下载</param>
  695. /// <param name="autoMainStoreDownload">如果是分店是否自动到总店服务器下载文件</param>
  696. /// <returns></returns>
  697. public string ReceiveFileCommandToServer(MemoryStream memoryMS = null, HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, string saveFileFullName = "", string serverFileFullName = "", BackgroundWorker backgroundWorker = null)
  698. {
  699. string tempMsg = "";
  700. // if (!isFileServerIng)
  701. {
  702. try
  703. {
  704. bool ret = false;
  705. TCP_NetworkClient myDownLoadClient = this.TFileClient;
  706. if (myDownLoadClient.AppState != HPSocketCS.Extended.AppState.Started)
  707. {
  708. myDownLoadClient.ConnectionServer();
  709. }
  710. if (myDownLoadClient.AppState == HPSocketCS.Extended.AppState.Started)
  711. {
  712. if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
  713. {
  714. //如果是下载头像时设置头像在服务器上的路径
  715. serverFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(serverFileFullName);
  716. }
  717. ServerFileInfo downloadFileInfo = myDownLoadClient.GetServerFileInfo(serverFileFullName);
  718. if (downloadFileInfo.IsExists)
  719. {
  720. if (memoryMS == null && saveFileFullName.Trim().Length > 0)
  721. {
  722. if (downloadFileInfo.FileSize < HPSocketCS.Sdk.FileMD5VerifySize && downloadFileInfo.FileMd5.Trim().Length > 0 && System.IO.File.Exists(saveFileFullName.Trim()))
  723. {
  724. string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(saveFileFullName.Trim());
  725. if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
  726. {
  727. ret = true;
  728. }
  729. else
  730. {
  731. ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
  732. }
  733. }
  734. else
  735. {
  736. ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
  737. }
  738. }
  739. else if (memoryMS != null)
  740. {
  741. string TempCachefilePath = TemporaryCachefilesPath + downloadFileInfo.FileMd5 + "_" + System.IO.Path.GetFileName(serverFileFullName);
  742. byte[] TempCachefileBytes = null;
  743. bool TempCachefileExists = false;
  744. try
  745. {
  746. if (System.IO.File.Exists(TempCachefilePath))
  747. {
  748. TempCachefileBytes= System.IO.File.ReadAllBytes(TempCachefilePath);
  749. TempCachefileExists = true;
  750. }
  751. }
  752. catch { }
  753. if (!TempCachefileExists)
  754. {
  755. MemoryStream recMemoryMS = myDownLoadClient.Client.DownloadMemoryStream(serverFileFullName, backgroundWorker);
  756. if (recMemoryMS != null)
  757. {
  758. try
  759. {
  760. if (!System.IO.Directory.Exists(TemporaryCachefilesPath))
  761. {
  762. System.IO.Directory.CreateDirectory(TemporaryCachefilesPath);
  763. }
  764. recMemoryMS.Position = 0;
  765. byte[] bytes = new byte[recMemoryMS.Length];
  766. recMemoryMS.Read(bytes, 0, bytes.Length);
  767. System.IO.File.WriteAllBytes(TempCachefilePath, bytes);
  768. Array.Clear(bytes, 0, bytes.Length);
  769. bytes = null;
  770. }
  771. catch { }
  772. recMemoryMS.WriteTo(memoryMS);
  773. memoryMS.Position = 0;
  774. recMemoryMS.Close();
  775. recMemoryMS.Dispose();
  776. recMemoryMS = null;
  777. ret = true;
  778. }
  779. }
  780. else {
  781. memoryMS.Write(TempCachefileBytes, 0, TempCachefileBytes.Length);
  782. System.Array.Clear(TempCachefileBytes, 0, TempCachefileBytes.Length);
  783. TempCachefileBytes = null;
  784. ret = true;
  785. }
  786. }
  787. else
  788. {
  789. return "下载请求错误";
  790. }
  791. }
  792. else
  793. {
  794. return downloadFileInfo.GetMsg;
  795. }
  796. }
  797. else
  798. {
  799. return "网络连接失败,请检查网络环境";
  800. }
  801. if (ret)
  802. {
  803. tempMsg = "下载成功";
  804. }
  805. else
  806. {
  807. tempMsg = "下载失败";
  808. }
  809. }
  810. catch (Exception ex)
  811. {
  812. tempMsg = "下载出错:" + ex.Message;
  813. }
  814. // finally
  815. // {
  816. // isFileServerIng = false;
  817. // }
  818. }
  819. return tempMsg;
  820. }
  821. #endregion
  822. }
  823. }