CommonLibrary.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading;
  7. namespace HPSocketCS.Extended
  8. {
  9. /// <summary>
  10. /// 程序运行状态
  11. /// </summary>
  12. public enum AppState
  13. {
  14. /// <summary>
  15. /// 启动中...
  16. /// </summary>
  17. Starting=0,
  18. /// <summary>
  19. /// 已启动
  20. /// </summary>
  21. Started=1,
  22. /// <summary>
  23. /// 停止中...
  24. /// </summary>
  25. Stoping=2,
  26. /// <summary>
  27. /// 已停止
  28. /// </summary>
  29. Stoped=3,
  30. /// <summary>
  31. /// 错误
  32. /// </summary>
  33. Error=4
  34. }
  35. /// <summary>
  36. /// 数据类型
  37. /// </summary>
  38. public enum DataType
  39. {
  40. /// <summary>
  41. /// 空数据
  42. /// </summary>
  43. None=0,
  44. /// <summary>
  45. /// 数组
  46. /// </summary>
  47. Array=1,
  48. /// <summary>
  49. /// 集合
  50. /// </summary>
  51. List=2,
  52. /// <summary>
  53. /// 文本信息
  54. /// </summary>
  55. Text=3,
  56. /// <summary>
  57. /// 序列化数据
  58. /// </summary>
  59. Serialization=4,
  60. /// <summary>
  61. /// 文件
  62. /// </summary>
  63. File=5,
  64. /// <summary>
  65. /// 显示窗体
  66. /// </summary>
  67. ShowForm=6,
  68. /// <summary>
  69. /// 推送消息
  70. /// </summary>
  71. PushMessage=7,
  72. /// <summary>
  73. /// 数据库信息处理
  74. /// </summary>
  75. SQLHelper=8,
  76. }
  77. /// <summary>
  78. /// 文件传输请求类型
  79. /// </summary>
  80. public enum FileRequestType
  81. {
  82. /// <summary>
  83. /// 上传
  84. /// </summary>
  85. Upload=0,
  86. /// <summary>
  87. /// 下载
  88. /// </summary>
  89. Download=1
  90. }
  91. /// <summary>
  92. /// 通信命令
  93. /// </summary>
  94. public enum TransferRequestCommand
  95. {
  96. /// <summary>
  97. /// 测试命令
  98. /// </summary>
  99. TestCommand=-1,
  100. /// <summary>
  101. /// 空命令
  102. /// </summary>
  103. EmptyCommand=0,
  104. /// <summary>
  105. /// 重要信息
  106. /// </summary>
  107. VitalInfo=1,
  108. /// <summary>
  109. /// 重要控制
  110. /// </summary>
  111. VitalControl = 2,
  112. /// <summary>
  113. /// 返回结果
  114. /// </summary>
  115. VitalControlOK=3,
  116. /// <summary>
  117. /// 文件传输
  118. /// </summary>
  119. FileTransfer=1000,
  120. /// <summary>
  121. /// 发送信息
  122. /// </summary>
  123. Message = 1001,
  124. /// <summary>
  125. /// 打开文件传输
  126. /// </summary>
  127. OpenFileTransfer = 1002,
  128. /// <summary>
  129. /// 关闭文件传输
  130. /// </summary>
  131. CloseFileTransfer = 1003,
  132. /// <summary>
  133. /// 上传用户头像
  134. /// </summary>
  135. UploadAvatar = 1004,
  136. /// <summary>
  137. /// 下载用户头像
  138. /// </summary>
  139. DownloadAvatar = 1005,
  140. /// <summary>
  141. /// 上传文件
  142. /// </summary>
  143. UploadFile = 1006,
  144. /// <summary>
  145. /// 下载文件
  146. /// </summary>
  147. DownloadFile = 1007,
  148. /// <summary>
  149. /// 获取文件信息
  150. /// </summary>
  151. GetFileInfo = 1008,
  152. /// <summary>
  153. /// 获取相片备份路径
  154. /// </summary>
  155. GetbackupPath = 1009,
  156. /// <summary>
  157. /// 获取相片保存路径
  158. /// </summary>
  159. GetSavePath = 1010,
  160. /// <summary>
  161. /// 上传客人头像
  162. /// </summary>
  163. UploadCustomersAvatar = 1011,
  164. /// <summary>
  165. /// 下载客人头像
  166. /// </summary>
  167. DownloadCustomersAvatar = 1012,
  168. /// <summary>
  169. /// 获取服务器软件信息,1.服务器ID 一搬为Lock短ID 2.类型 是总服务器还是分店服务器 3.软件业务类型 4.功能类型 5.服务器版本号
  170. /// </summary>
  171. GetServerSoftwareInfo = 1013,
  172. /// <summary>
  173. /// 获取数据库连接字符串
  174. /// </summary>
  175. GetDataConne = 1014,
  176. /// <summary>
  177. /// 获取相片保存路径集合 用于客户端读取订单相片
  178. /// </summary>
  179. GetSavePhotoPathList = 1015,
  180. /// <summary>
  181. /// 获取服务器时间 带有服务器版本号 用于检查客户端是否需要更新
  182. /// </summary>
  183. ServerDateTime = 1016,
  184. /// <summary>
  185. /// 删除文件
  186. /// </summary>
  187. DeleteFile = 1017,
  188. /// <summary>
  189. /// 生成缩略图
  190. /// </summary>
  191. GenerateThumbnails = 1018,
  192. /// <summary>
  193. /// 导入相片请求
  194. /// </summary>
  195. ImportPhotos = 1019,
  196. /// <summary>
  197. /// 选片请求
  198. /// </summary>
  199. SelectPhotos = 1020,
  200. /// <summary>
  201. /// 查看相片请求
  202. /// </summary>
  203. LookPhotos = 1021,
  204. /// <summary>
  205. /// 更新订单请求
  206. /// </summary>
  207. UpdateOrder = 1022,
  208. /// <summary>
  209. /// 获取最新客户端皮肤图片
  210. /// </summary>
  211. GetUpdateClientSkinImage = 1023,
  212. /// <summary>
  213. /// 删除原始相片
  214. /// </summary>
  215. DeleteOriginalPhoto = 1024,
  216. /// <summary>
  217. /// 删除备份相片
  218. /// </summary>
  219. DeleteBackupPhoto = 1025,
  220. /// <summary>
  221. /// 获取客户端列表
  222. /// </summary>
  223. GetClientList = 1026,
  224. /// <summary>
  225. /// 刷新客户连接
  226. /// </summary>
  227. RefreshClientList = 1027,
  228. /// <summary>
  229. /// 获取数据
  230. /// </summary>
  231. GetBigData = 1028,
  232. /// <summary>
  233. /// 获取文件列表
  234. /// </summary>
  235. GeTFileList = 1029,
  236. /// <summary>
  237. /// 获取目录列表
  238. /// </summary>
  239. GetDirectoryList = 1030,
  240. /// <summary>
  241. /// 删除目录
  242. /// </summary>
  243. DeleteDirectory = 1031,
  244. /// <summary>
  245. /// 获取备份记录
  246. /// </summary>
  247. GetBackupRecords=1032,
  248. /// <summary>
  249. /// 获取总店数据库备份记录
  250. /// </summary>
  251. GetMainShopBackupRecords=1033,
  252. /// <summary>
  253. /// 获取总店测试信息
  254. /// </summary>
  255. MainStoreTestInfo=1034,
  256. /// <summary>
  257. /// SQL数据库操作
  258. /// </summary>
  259. SQLHelperData=1035,
  260. /// <summary>
  261. /// 序例化数据传输
  262. /// </summary>
  263. SerializationData=1036,
  264. /// <summary>
  265. /// 安装数据库
  266. /// </summary>
  267. InstallationDatabase=1037,
  268. /// <summary>
  269. /// 升级数据库
  270. /// </summary>
  271. UpgradeDatabase = 1038,
  272. /// <summary>
  273. /// 刷新云服务器数据
  274. /// </summary>
  275. RefreshCloudServerData=1039,
  276. /// <summary>
  277. /// 云登录
  278. /// </summary>
  279. CloudLoginIP=1040,
  280. /// <summary>
  281. /// 提效软件信息
  282. /// </summary>
  283. SubmitSoftwareInfo=1041,
  284. /// <summary>
  285. /// 获取总店服务器软件信息
  286. /// </summary>
  287. GetMainStoreServerSoftwareInfo = 1042,
  288. /// <summary>
  289. /// 备份数据库
  290. /// </summary>
  291. BackupDatabase=1043,
  292. /// <summary>
  293. /// 客户端在线连接
  294. /// </summary>
  295. ClientOnlineConnection=1044,
  296. }
  297. /// <summary>
  298. /// SQLHelper请求类型
  299. /// </summary>
  300. public enum SQLHelperRequestType
  301. {
  302. /// <summary>
  303. /// 执行查询语句,返回DataSet
  304. /// </summary>
  305. QueryReturnDataSet= 0,
  306. /// <summary>
  307. /// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
  308. /// </summary>
  309. ExecuteScalar=1,
  310. /// <summary>
  311. /// 对连接执行 Transact-SQL 语句并返回受影响的行数。
  312. /// </summary>
  313. ExecuteNonQuery=2,
  314. /// <summary>
  315. /// 执行存储过程
  316. /// </summary>
  317. RunProcedure=3,
  318. /// <summary>
  319. /// 执行事务
  320. /// </summary>
  321. ExecuteSqlTran=4,
  322. /// <summary>
  323. /// 检查数据库连接 是否能正常连接数据
  324. /// </summary>
  325. ExistsSqlConn=5,
  326. }
  327. public delegate void DelegateExecuteThreadStart(ReturnResultObject argumentResult);
  328. public class CommonLibrary
  329. {
  330. public CommonLibrary() {
  331. }
  332. /// <summary>
  333. /// WebForm和WinForm通用的取当前根目录的方法
  334. /// </summary>
  335. public static string BasePath
  336. {
  337. get
  338. {
  339. System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
  340. //WebDev.WebServer visual studio web server
  341. //xxx.vhost Winform
  342. //w3wp IIS7
  343. //aspnet_wp IIS6
  344. string processName = p.ProcessName.ToLower();
  345. string retPath = System.Windows.Forms.Application.StartupPath;
  346. if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
  347. {
  348. if (System.Web.HttpContext.Current != null)
  349. retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
  350. else //当控件在定时器的触发程序中使用时就为空
  351. {
  352. retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
  353. }
  354. }
  355. return retPath;
  356. }
  357. }
  358. /// <summary>
  359. /// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
  360. /// </summary>
  361. /// <param name="directoryPath"></param>
  362. /// <returns></returns>
  363. public static string GetFullDirectoryPath(string directoryPath)
  364. {
  365. if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
  366. {
  367. directoryPath = directoryPath + "\\";
  368. }
  369. return directoryPath;
  370. }
  371. /// <summary>
  372. /// 全局ID
  373. /// </summary>
  374. /// <returns></returns>
  375. public static long GenerateId()
  376. {
  377. byte[] buffer = Guid.NewGuid().ToByteArray();
  378. return BitConverter.ToInt64(buffer, 0);
  379. }
  380. static string _ServerVersionNumber = "1.0";
  381. /// <summary>
  382. /// 服务器版本号
  383. /// </summary>
  384. public static string ServerVersionNumber
  385. {
  386. get { return CommonLibrary._ServerVersionNumber; }
  387. set { CommonLibrary._ServerVersionNumber = value; }
  388. }
  389. static string _ClientMarkID = "ServerHosts";
  390. /// <summary>
  391. /// 客户端标识ID
  392. /// </summary>
  393. public static string ClientMarkID
  394. {
  395. get { return CommonLibrary._ClientMarkID; }
  396. set { CommonLibrary._ClientMarkID = value; }
  397. }
  398. static string _ClientMarkName = "服务器主机";
  399. /// <summary>
  400. /// 客户端标识名称
  401. /// </summary>
  402. public static string ClientMarkName
  403. {
  404. get { return CommonLibrary._ClientMarkName; }
  405. set { CommonLibrary._ClientMarkName = value; }
  406. }
  407. static string _LoginUsername = "未知用户";
  408. /// <summary>
  409. ///登录用户名
  410. /// </summary>
  411. public static string LoginUsername
  412. {
  413. get { return CommonLibrary._LoginUsername; }
  414. set { CommonLibrary._LoginUsername = value; }
  415. }
  416. private static string _HardwareCode = "HardwareCode";
  417. /// <summary>
  418. /// 硬件码
  419. /// </summary>
  420. public static string HardwareCode
  421. {
  422. get { return CommonLibrary._HardwareCode; }
  423. set { CommonLibrary._HardwareCode = value; }
  424. }
  425. #region 发送数据时的方法
  426. /// <summary>
  427. /// 获取发送数据时的头协议结构
  428. /// </summary>
  429. /// <param name="ConnId">连接ID</param>
  430. /// <param name="addedDataPtr">附加数据</param>
  431. /// <param name="dType">要发送的数据类型</param>
  432. /// <param name="requestCommand">请求命令</param>
  433. /// <param name="transportID">传输标识符</param>
  434. /// <param name="isTail">是否有协议尾信息</param>
  435. /// <returns></returns>
  436. public static TcpHeadInfo GetProtocolHeader(IntPtr ConnId, IntPtr addedDataPtr, DataType dType, TransferRequestCommand requestCommand, Int64 transportID, bool isTail = false)
  437. {
  438. HPSocketCS.Extended.ClientInfo ci = null;
  439. try
  440. {
  441. // IntPtr.Zero;
  442. // ci 就是accept里传入的附加数据了
  443. if (addedDataPtr != IntPtr.Zero)
  444. {
  445. ci = (HPSocketCS.Extended.ClientInfo)Marshal.PtrToStructure(addedDataPtr, typeof(HPSocketCS.Extended.ClientInfo));
  446. }
  447. }
  448. catch { }
  449. TcpHeadInfo protocolHeader = new TcpHeadInfo();
  450. protocolHeader.ConnId = ConnId.ToInt32();
  451. protocolHeader.Hostname = System.Net.Dns.GetHostName();
  452. protocolHeader.MsgDataType = (int)dType;
  453. protocolHeader.RequestCommand = (int)requestCommand;
  454. protocolHeader.IntactSize = 0;
  455. protocolHeader.ServerNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  456. protocolHeader.ClientMarkID = CommonLibrary.ClientMarkID;
  457. protocolHeader.ClientMarkName = CommonLibrary.ClientMarkName;
  458. protocolHeader.ServerVersionNumber = CommonLibrary.ServerVersionNumber;
  459. protocolHeader.LoginUsername = CommonLibrary.LoginUsername;
  460. protocolHeader.HardwareCode = CommonLibrary.HardwareCode;
  461. protocolHeader.TransportEnd = true;
  462. protocolHeader.TransportStart = true;
  463. protocolHeader.TransportID = transportID;
  464. protocolHeader.IsTail = isTail;
  465. if (ci != null)
  466. {
  467. protocolHeader.IPAddress = ci.IpAddress;
  468. protocolHeader.Port = ci.Port;
  469. }
  470. return protocolHeader;
  471. }
  472. /// <summary>
  473. /// 写日志 调试时使用
  474. /// </summary>
  475. /// <param name="txt">日志内容</param>
  476. /// <param name="fullPath">日志文件全路径</param>
  477. public static void WriteLogs(string txt)
  478. {
  479. try
  480. {
  481. string fullPath = BasePath + "\\Logs\\MainLogs\\"+DateTime.Now.ToString("yyyy-MM-dd")+".txt";
  482. if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(fullPath)))
  483. {
  484. System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
  485. }
  486. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, Encoding.UTF8))
  487. {
  488. sw.WriteLine("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "】" + txt);
  489. sw.Flush();
  490. sw.Close();
  491. }
  492. }
  493. catch { }
  494. }
  495. /// <summary>
  496. /// 自动拆包并加上包头 包尾
  497. /// </summary>
  498. /// <param name="packBytes">要拆分的数据包</param>
  499. /// <param name="pkgHeader">包头结构</param>
  500. /// <param name="maxPackSize">每包的最大大小</param>
  501. /// <returns>返回拆分后的数据包集合</returns>
  502. public static System.IO.BufferedStream AutoUnpackingAndAddPkgHeader(byte[] sendPackBytes, TcpHeadInfo pkgHeader, TcpTailInfo pkgTail, int maxPackSize)
  503. {
  504. // WriteLogs("压缩前的长度:" + packBytes.Length);
  505. byte[] packBytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataCompressionRetBytes(sendPackBytes);
  506. System.IO.MemoryStream retDataMstream = new System.IO.MemoryStream();
  507. System.IO.BufferedStream buffStream = new System.IO.BufferedStream(retDataMstream, Sdk.PacketBufferSize * 2);
  508. try
  509. {
  510. // WriteLogs("压缩后的长度:" + packBytes.Length);
  511. // byte[] tempbytes=HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(packBytes);
  512. // string tempstr = Encoding.UTF8.GetString(tempbytes, 0, tempbytes.Length);
  513. // WriteLogs("压缩后解压还原后的信息:"+tempstr);
  514. // List<byte[]> byteList = new List<byte[]>();
  515. pkgHeader.IntactSize = packBytes.Length;
  516. pkgHeader.ServerNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  517. // 包头大小
  518. int pkgHeaderSize = Marshal.SizeOf(pkgHeader);
  519. int pkgTailSize = 0;
  520. if (pkgHeader.IsTail)
  521. {
  522. pkgTailSize = Marshal.SizeOf(pkgTail);
  523. }
  524. //附加协议数据包大小
  525. int AppendPakSize = pkgHeaderSize + pkgTailSize;
  526. if (packBytes.Length + AppendPakSize <= maxPackSize)
  527. {
  528. pkgHeader.TransportStart = true;
  529. pkgHeader.TransportEnd = true;
  530. //包头数据
  531. byte[] pkgHeaderBytes = StructureToByte<TcpHeadInfo>(pkgHeader);
  532. // 组合最终发送的封包 (封包头封包体)
  533. byte[] sendBytes = null;
  534. if (pkgHeader.IsTail)
  535. {
  536. byte[] tailBytes = StructureToByte<TcpTailInfo>(pkgTail);
  537. sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, packBytes, tailBytes);
  538. tailBytes = null;
  539. }
  540. else
  541. {
  542. sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, packBytes, null);
  543. }
  544. buffStream.Write(sendBytes, 0, sendBytes.Length);
  545. //retDataMstream.Write(sendBytes, 0, sendBytes.Length);
  546. // byteList.Add(sendBytes);
  547. sendBytes = null;
  548. pkgHeaderBytes = null;
  549. }
  550. else
  551. {
  552. //每包大小
  553. int packSize = Convert.ToInt32(maxPackSize - AppendPakSize);
  554. //可拆包数
  555. int packCount = packBytes.Length / packSize;
  556. if (packBytes.Length % packSize > 0)
  557. {
  558. packCount = packCount + 1;
  559. }
  560. for (int i = 0; i < packCount; i++)
  561. {
  562. byte[] tempPackBytes = new byte[packSize];
  563. if (i == 0)
  564. {
  565. pkgHeader.TransportStart = true;
  566. pkgHeader.TransportEnd = false;
  567. }
  568. else
  569. {
  570. pkgHeader.TransportStart = false;
  571. pkgHeader.TransportEnd = false;
  572. }
  573. if (i + 1 == packCount)
  574. {
  575. pkgHeader.TransportEnd = true;
  576. tempPackBytes = new byte[packBytes.Length - packSize * i];
  577. }
  578. Array.Copy(packBytes, i * packSize, tempPackBytes, 0, tempPackBytes.Length);
  579. //包头数据
  580. byte[] pkgHeaderBytes = StructureToByte<TcpHeadInfo>(pkgHeader);
  581. // 组合最终发送的封包 (封包头封包体)
  582. byte[] sendBytes = null;
  583. if (pkgHeader.IsTail)
  584. {
  585. byte[] tailBytes = StructureToByte<TcpTailInfo>(pkgTail);
  586. sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, tempPackBytes, tailBytes);
  587. tailBytes = null;
  588. }
  589. else
  590. {
  591. sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, tempPackBytes, null);
  592. }
  593. buffStream.Write(sendBytes, 0, sendBytes.Length);
  594. //retDataMstream.Write(sendBytes, 0, sendBytes.Length);
  595. // byteList.Add(sendBytes);
  596. pkgHeaderBytes = null;
  597. sendBytes = null;
  598. }
  599. }
  600. }
  601. catch
  602. {
  603. }
  604. buffStream.Flush();
  605. buffStream.Position = 0;
  606. retDataMstream.Position = 0;
  607. Array.Clear(packBytes, 0, packBytes.Length);
  608. packBytes = null;
  609. //return byteList;
  610. return buffStream;
  611. }
  612. /// <summary>
  613. /// 由结构体转换为byte数组
  614. /// </summary>
  615. public static byte[] StructureToByte<T>(T structure)
  616. {
  617. int size = Marshal.SizeOf(typeof(T));
  618. byte[] buffer = new byte[size];
  619. IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
  620. try
  621. {
  622. Marshal.StructureToPtr(structure, bufferIntPtr, true);
  623. Marshal.Copy(bufferIntPtr, buffer, 0, size);
  624. }
  625. finally
  626. {
  627. Marshal.FreeHGlobal(bufferIntPtr);
  628. }
  629. return buffer;
  630. }
  631. /// <summary>
  632. /// 组合最终发送的封包 (封包头+封包体)
  633. /// </summary>
  634. /// <param name="headerBytes">封包头</param>
  635. /// <param name="bodyBytes">封包体</param>
  636. /// <returns></returns>
  637. public static byte[] GetSendBuffer(byte[] headerBytes, byte[] bodyBytes,byte[] tailBytes)
  638. {
  639. // IntPtr ptr = IntPtr.Zero;
  640. byte[] retBytes = null;
  641. try
  642. {
  643. int bufferSize = headerBytes.Length + bodyBytes.Length;
  644. if (tailBytes != null)
  645. {
  646. bufferSize= bufferSize + tailBytes.Length;
  647. }
  648. retBytes = new byte[bufferSize];
  649. // 拷贝包头到缓冲区首部
  650. Array.Copy(headerBytes, 0, retBytes, 0, headerBytes.Length);
  651. //Marshal.Copy(headerBytes, 0, ptr, headerBytes.Length);
  652. // 拷贝包体到缓冲区剩余部分
  653. Array.Copy(bodyBytes, 0, retBytes, headerBytes.Length, bodyBytes.Length);
  654. if (tailBytes != null)
  655. {
  656. // 拷贝包尾到缓冲区剩余部分
  657. Array.Copy(tailBytes, 0, retBytes, headerBytes.Length + bodyBytes.Length, tailBytes.Length);
  658. }
  659. return retBytes;
  660. }
  661. finally
  662. {
  663. headerBytes = null;
  664. bodyBytes = null;
  665. tailBytes = null;
  666. }
  667. }
  668. #endregion
  669. #region 接收数据时的方法
  670. /// <summary>
  671. /// 接收数据集合
  672. /// </summary>
  673. List<ReceiveData> ReceiveDataList = new List<ReceiveData>();
  674. /// <summary>
  675. /// 获取本次通信的收接数据处理对象 如果没有时返回null
  676. /// </summary>
  677. /// <param name="tcpInfo"></param>
  678. /// <returns></returns>
  679. public ReceiveData GetReceiveData(TcpHeadInfo tcpInfo)
  680. {
  681. ReceiveData retRData = null;
  682. lock (ReceiveDataList)
  683. {
  684. foreach (ReceiveData rData in ReceiveDataList)
  685. {
  686. if (rData.ReceiveRemoteClientInfo.ConnId == tcpInfo.ConnId && rData.ReceiveRemoteClientInfo.TransportID == tcpInfo.TransportID)
  687. {
  688. retRData = rData;
  689. break;
  690. }
  691. }
  692. return retRData;
  693. }
  694. }
  695. /// <summary>
  696. /// 添加接收数据处理对象
  697. /// </summary>
  698. /// <param name="rData"></param>
  699. public void AddReceiveData(ReceiveData rData)
  700. {
  701. lock (ReceiveDataList)
  702. {
  703. this.ReceiveDataList.Add(rData);
  704. }
  705. }
  706. /// <summary>
  707. /// 移除接收数据处理对象
  708. /// </summary>
  709. /// <param name="rData"></param>
  710. public void RemoveReceiveDataData(ReceiveData rData)
  711. {
  712. try
  713. {
  714. lock (ReceiveDataList)
  715. {
  716. ReceiveDataList.Remove(rData);
  717. }
  718. if (rData != null)
  719. {
  720. rData.Dispose();
  721. // rData.ReceiveDataMstream.Close();
  722. // rData.ReceiveDataMstream.Dispose();
  723. // rData.ReceiveDataMstream = null;
  724. rData = null;
  725. }
  726. }
  727. catch { }
  728. finally
  729. {
  730. System.GC.Collect();
  731. }
  732. }
  733. /// <summary>
  734. /// 清除所有无效连接资源
  735. /// </summary>
  736. /// <param name="connId"></param>
  737. public void ClearAllInvalidResource()
  738. {
  739. lock (ReceiveDataList)
  740. {
  741. int count = ReceiveDataList.Count;
  742. for (int i = 0; i < count; i++)
  743. {
  744. DispenseReceiveData(ReceiveDataList[i]);
  745. }
  746. ReceiveDataList.Clear();
  747. }
  748. }
  749. public void DispenseReceiveData(ReceiveData rData)
  750. {
  751. lock (ReceiveDataList)
  752. {
  753. ReceiveDataList.Remove(rData);
  754. if (rData != null)
  755. {
  756. /* rData.ReceiveDataMstream.Close();
  757. rData.ReceiveDataMstream.Dispose();
  758. rData.ReceiveDataMstream = null;*/
  759. rData.Dispose();
  760. rData = null;
  761. }
  762. }
  763. }
  764. /// <summary>
  765. /// 清除无效连接资源
  766. /// </summary>
  767. /// <param name="connId"></param>
  768. public void ClearInvalidConnectionResource(IntPtr connId)
  769. {
  770. try
  771. {
  772. List<ReceiveData> retRDatalist = new List<ReceiveData>();
  773. lock (ReceiveDataList)
  774. {
  775. foreach (ReceiveData rData in ReceiveDataList)
  776. {
  777. if (rData.ReceiveRemoteClientInfo.ConnId == connId.ToInt32())
  778. {
  779. retRDatalist.Add(rData);
  780. }
  781. }
  782. for (int i = 0; i < retRDatalist.Count; i++)
  783. {
  784. DispenseReceiveData(retRDatalist[i]);
  785. }
  786. retRDatalist.Clear();
  787. }
  788. }
  789. catch
  790. {
  791. }
  792. finally
  793. {
  794. System.GC.Collect();
  795. }
  796. }
  797. #endregion
  798. #region 客户端接收到的数据缓存处理方法
  799. Dictionary<Int64, ReceiveCacheBuffer> _ServerToClientCacheBufferList = new Dictionary<Int64, ReceiveCacheBuffer>();
  800. /// <summary>
  801. /// 收到服务发送回来的数据集合
  802. /// </summary>
  803. public Dictionary<Int64, ReceiveCacheBuffer> ServerToClientCacheBufferList
  804. {
  805. get { return _ServerToClientCacheBufferList; }
  806. set { _ServerToClientCacheBufferList = value; }
  807. }
  808. /// <summary>
  809. /// 获取收到的数据缓存区对象
  810. /// </summary>
  811. /// <param name="cid">数据传输标识符</param>
  812. /// <returns></returns>
  813. public ReceiveCacheBuffer GetReceiveCacheBuffer(Int64 cid)
  814. {
  815. lock (_ServerToClientCacheBufferList)
  816. {
  817. ReceiveCacheBuffer retCacheBuffer = null;
  818. if (_ServerToClientCacheBufferList.TryGetValue(cid, out retCacheBuffer))
  819. {
  820. return retCacheBuffer;
  821. }
  822. else
  823. {
  824. return retCacheBuffer;
  825. }
  826. }
  827. }
  828. /// <summary>
  829. /// 添加数据缓存区对象到集合中
  830. /// </summary>
  831. /// <param name="cid">数据传输标识符</param>
  832. /// <param name="rCacheBuffer"></param>
  833. public void AddCacheBufferToList(Int64 cid, ReceiveCacheBuffer rCacheBuffer)
  834. {
  835. lock (_ServerToClientCacheBufferList)
  836. {
  837. if (!this._ServerToClientCacheBufferList.ContainsKey(cid))
  838. {
  839. this._ServerToClientCacheBufferList.Add(cid, rCacheBuffer);
  840. }
  841. /* IntPtr ptrbytes = GetReceiveBytes(cid);
  842. if (ptrbytes != IntPtr.Zero) {
  843. Marshal.FreeHGlobal(ptrbytes);
  844. ptrbytes = IntPtr.Zero;
  845. }
  846. DataHeader dhead = new DataHeader();
  847. dhead.Length = bytes.Length;
  848. int bufferSize = bytes.Length+Marshal.SizeOf(dhead);
  849. byte[] dheadBytes = StructureToByte<DataHeader>(dhead);
  850. ptrbytes = Marshal.AllocHGlobal(bufferSize);
  851. // 拷贝头数据到缓冲区
  852. Marshal.Copy(dheadBytes, 0, ptrbytes, dheadBytes.Length);
  853. // 拷贝数据到缓冲区剩余部分
  854. Marshal.Copy(bytes, 0, ptrbytes + dheadBytes.Length, bytes.Length);
  855. _ServerToClientByteList.Add(cid, ptrbytes);
  856. bytes = null;*/
  857. }
  858. }
  859. /// <summary>
  860. /// 移除指定的数据缓存区对象
  861. /// </summary>
  862. /// <param name="cid"></param>
  863. public void RemoveServerToClientByteList(Int64 cid)
  864. {
  865. try
  866. {
  867. lock (_ServerToClientCacheBufferList)
  868. {
  869. try
  870. {
  871. ReceiveCacheBuffer rCacheBuffer = GetReceiveCacheBuffer(cid);
  872. if (rCacheBuffer != null)
  873. {
  874. rCacheBuffer.Dispose();
  875. rCacheBuffer = null;
  876. }
  877. }
  878. catch { }
  879. _ServerToClientCacheBufferList.Remove(cid);
  880. }
  881. }
  882. finally {
  883. System.GC.Collect();
  884. }
  885. }
  886. /// <summary>
  887. /// 清除所有数据缓存区对象
  888. /// </summary>
  889. public void ClearAllServerToClientByteList()
  890. {
  891. try
  892. {
  893. lock (_ServerToClientCacheBufferList)
  894. {
  895. foreach (long key in _ServerToClientCacheBufferList.Keys)
  896. {
  897. try
  898. {
  899. _ServerToClientCacheBufferList[key].Dispose();
  900. }
  901. catch { }
  902. }
  903. _ServerToClientCacheBufferList.Clear();
  904. }
  905. }
  906. finally
  907. {
  908. System.GC.Collect();
  909. }
  910. }
  911. #endregion
  912. /// <summary>
  913. /// 进程进度报告
  914. /// </summary>
  915. /// <param name="sumCount">运行总计数器</param>
  916. /// <param name="currentCount">当前进度值</param>
  917. /// <param name="msg">报告信息</param>
  918. public static void SetBackgroundWorker(long sumCount, long currentCount, string msg = "", System.ComponentModel.BackgroundWorker backgroundWorker = null)
  919. {
  920. if (backgroundWorker != null)
  921. {
  922. try
  923. {
  924. int currentProgres = Convert.ToInt32(1000f / sumCount * currentCount);
  925. //WriteLogs("共 " + sumCount + " 字节 已接收 " + currentCount + " 字节 当前 " + currentProgres +" %");
  926. backgroundWorker.ReportProgress(currentProgres, msg);
  927. }
  928. catch { }
  929. }
  930. }
  931. /// <summary>
  932. /// 获取VC++ MD5
  933. /// </summary>
  934. /// <param name="str"></param>
  935. /// <returns></returns>
  936. public static string GetVCFileMD5(string filePath)
  937. {
  938. string retMd5Value = "";
  939. byte[] retByte = new byte[32];
  940. IntPtr bufferIntPtr_File = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
  941. if (Environment.Is64BitProcess)
  942. {
  943. if (VCMD5_X64.GetFileMD5(filePath, bufferIntPtr_File, 32) == 0)
  944. {
  945. System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr_File, retByte, 0, 32);
  946. retMd5Value = Encoding.UTF8.GetString(retByte);
  947. }
  948. }
  949. else
  950. {
  951. if (VCMD5_X86.GetFileMD5(filePath, bufferIntPtr_File, 32) == 0)
  952. {
  953. System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr_File, retByte, 0, 32);
  954. retMd5Value = Encoding.UTF8.GetString(retByte);
  955. }
  956. }
  957. System.Array.Clear(retByte, 0, retByte.Length);
  958. retByte = null;
  959. if (bufferIntPtr_File != IntPtr.Zero)
  960. {
  961. System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr_File);
  962. }
  963. return retMd5Value;
  964. }
  965. /// <summary>
  966. /// 获取VC++ MD5
  967. /// </summary>
  968. /// <param name="str"></param>
  969. /// <returns></returns>
  970. public static string GetVCByteMD5(byte[] bytes)
  971. {
  972. string retMd5Value = "";
  973. byte[] retByte = new byte[32];
  974. IntPtr lpBytes = System.Runtime.InteropServices.Marshal.AllocHGlobal(bytes.Length);
  975. System.Runtime.InteropServices.Marshal.Copy(bytes, 0, lpBytes, bytes.Length);
  976. IntPtr bufferIntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
  977. if (Environment.Is64BitProcess)
  978. {
  979. if (VCMD5_X64.GetByteMD5(lpBytes, bytes.Length, bufferIntPtr) == 0)
  980. {
  981. System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
  982. retMd5Value = Encoding.UTF8.GetString(retByte);
  983. }
  984. }
  985. else
  986. {
  987. if (VCMD5_X86.GetByteMD5(lpBytes, bytes.Length, bufferIntPtr) == 0)
  988. {
  989. System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
  990. retMd5Value = Encoding.UTF8.GetString(retByte);
  991. }
  992. }
  993. if (bufferIntPtr != IntPtr.Zero)
  994. {
  995. System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr);
  996. }
  997. if (lpBytes != IntPtr.Zero)
  998. {
  999. System.Runtime.InteropServices.Marshal.FreeHGlobal(lpBytes);
  1000. }
  1001. return retMd5Value;
  1002. }
  1003. /// <summary>
  1004. /// 获取VC++ MD5
  1005. /// </summary>
  1006. /// <param name="str"></param>
  1007. /// <returns></returns>
  1008. public static string GetVCStringMD5(string str)
  1009. {
  1010. string retMd5Value = "";
  1011. byte[] retByteUtf8 = Encoding.UTF8.GetBytes(str);
  1012. string Gb2313 = Encoding.GetEncoding("gb2312").GetString(retByteUtf8);
  1013. byte[] retByte = new byte[32];
  1014. IntPtr bufferIntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
  1015. if (Environment.Is64BitProcess)
  1016. {
  1017. if (VCMD5_X64.GetStringMD5(Gb2313, bufferIntPtr, 32) == 0)
  1018. {
  1019. System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
  1020. retMd5Value = Encoding.UTF8.GetString(retByte);
  1021. }
  1022. }
  1023. else
  1024. {
  1025. if (VCMD5_X86.GetStringMD5(Gb2313, bufferIntPtr, 32) == 0)
  1026. {
  1027. System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
  1028. retMd5Value = Encoding.UTF8.GetString(retByte);
  1029. }
  1030. }
  1031. if (bufferIntPtr != IntPtr.Zero)
  1032. {
  1033. System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr);
  1034. }
  1035. return retMd5Value;
  1036. }
  1037. /// <summary>
  1038. /// 是否FIPS出错
  1039. /// </summary>
  1040. static bool isFIPSError = false;
  1041. /// <summary>
  1042. /// 获取文件的MD5值
  1043. /// </summary>
  1044. /// <param name="fileName"></param>
  1045. /// <returns></returns>
  1046. public static string GetMD5HashFromFile(byte[] byets)
  1047. {
  1048. try
  1049. {
  1050. if (!isFIPSError)
  1051. {
  1052. try
  1053. {
  1054. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  1055. byte[] retVal = md5.ComputeHash(byets);
  1056. StringBuilder sb = new StringBuilder();
  1057. for (int i = 0; i < retVal.Length; i++)
  1058. {
  1059. sb.Append(retVal[i].ToString("x2"));
  1060. }
  1061. byets = null;
  1062. return sb.ToString();
  1063. }
  1064. catch //(Exception ex)
  1065. {
  1066. isFIPSError = true;
  1067. return GetVCByteMD5(byets);
  1068. //throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  1069. }
  1070. }
  1071. else
  1072. {
  1073. return GetVCByteMD5(byets);
  1074. }
  1075. }
  1076. catch (Exception ex)
  1077. {
  1078. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// 获取文件的MD5值
  1083. /// </summary>
  1084. /// <param name="fileName"></param>
  1085. /// <returns></returns>
  1086. public static string GetMD5HashFromFile(string fileName)
  1087. {
  1088. try
  1089. {
  1090. if (!isFIPSError)
  1091. {
  1092. System.IO.FileStream file = null;
  1093. try
  1094. {
  1095. file = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
  1096. }
  1097. catch (Exception ex)
  1098. {
  1099. throw new Exception("验证MD5时打开文件出失败:" + ex.Message);
  1100. }
  1101. try
  1102. {
  1103. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  1104. byte[] retVal = md5.ComputeHash(file);
  1105. StringBuilder sb = new StringBuilder();
  1106. for (int i = 0; i < retVal.Length; i++)
  1107. {
  1108. sb.Append(retVal[i].ToString("x2"));
  1109. }
  1110. System.Array.Clear(retVal, 0, retVal.Length);
  1111. retVal = null;
  1112. return sb.ToString();
  1113. }
  1114. catch //(Exception ex)
  1115. {
  1116. isFIPSError = true;
  1117. return GetVCFileMD5(fileName);
  1118. // throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  1119. }
  1120. finally
  1121. {
  1122. file.Close();
  1123. file.Dispose();
  1124. }
  1125. }
  1126. else
  1127. {
  1128. return GetVCFileMD5(fileName);
  1129. }
  1130. }
  1131. catch (Exception ex)
  1132. {
  1133. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  1134. }
  1135. }
  1136. /// <summary>
  1137. /// 验证两个MD5值是否相同
  1138. /// </summary>
  1139. /// <param name="md51"></param>
  1140. /// <param name="md52"></param>
  1141. /// <returns></returns>
  1142. public static bool VerifyMd5Hash(string md51, string md52)
  1143. {
  1144. if (md51.Trim().ToUpper() == md52.Trim().ToUpper())
  1145. {
  1146. return true;
  1147. }
  1148. else
  1149. {
  1150. return false;
  1151. }
  1152. }
  1153. }
  1154. public class VCMD5_X86
  1155. {
  1156. [System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
  1157. public static extern int GetStringMD5(string lpString, IntPtr pResult, int length);
  1158. [System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
  1159. public static extern int GetFileMD5(string lpFilepath, IntPtr pResult, int length);
  1160. [System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
  1161. public static extern int GetByteMD5(IntPtr lpBytes, int nInputlen, IntPtr pResult);
  1162. }
  1163. public class VCMD5_X64
  1164. {
  1165. [System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
  1166. public static extern int GetStringMD5(string lpString, IntPtr pResult, int length);
  1167. [System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
  1168. public static extern int GetFileMD5(string lpFilepath, IntPtr pResult, int length);
  1169. [System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
  1170. public static extern int GetByteMD5(IntPtr lpBytes, int nInputlen, IntPtr pResult);
  1171. }
  1172. }