EapSocketServer.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using Cksoft.Unity;
  4. using DllEapDal;
  5. using DllEapEntity;
  6. using Microsoft.Extensions.Configuration;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Threading;
  15. namespace DllEapFileUpload
  16. {
  17. public class EapSocketServer : IEapScoketServer
  18. {
  19. Thread threadWatch = null; // 负责监听客户端连接请求的 线程;
  20. Socket socketWatch = null;
  21. Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
  22. Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
  23. //string savepath = string.Empty;
  24. //byte[] filebytes;
  25. //string downloadpath = string.Empty;
  26. //byte[] downfilebytes;
  27. //string setip = string.Empty;
  28. //int setport;
  29. public IConfiguration Configuration;
  30. //static string serverpath = string.Empty;
  31. public bool Start(ref string errinfo)
  32. {
  33. // 创建负责监听的套接字,注意其中的参数;
  34. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  35. //var builder = new ConfigurationBuilder()
  36. // .SetBasePath(Directory.GetCurrentDirectory())
  37. // .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
  38. //Configuration = builder.Build();
  39. //setport = int.Parse(Configuration["EapSocket:SetPort"].ToString());
  40. ////serverpath = Configuration["EapSocket:SaveToServerPath"].ToString();
  41. //try
  42. //{
  43. // setip = getEapIpv4();
  44. //}
  45. //catch (Exception)
  46. //{
  47. // setip = Configuration["EapSocket:SetIp"].ToString();
  48. //}
  49. // 获得文本框中的IP对象;
  50. //IPAddress address = IPAddress.Parse(setip);
  51. // 创建包含ip和端口号的网络节点对象;
  52. IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 5777);
  53. try
  54. {
  55. // 将负责监听的套接字绑定到唯一的ip和端口上;
  56. socketWatch.Bind(endPoint);
  57. }
  58. catch (SocketException se)
  59. {
  60. errinfo = "异常:" + se.Message;
  61. LogBLL.Err(errinfo);
  62. Close(ref errinfo);
  63. return false;
  64. }
  65. // 设置监听队列的长度;
  66. socketWatch.Listen(10);
  67. // 创建负责监听的线程;
  68. threadWatch = new Thread(WatchConnecting);
  69. threadWatch.IsBackground = true;
  70. threadWatch.Start();
  71. errinfo = "IEapScoketServer服务器启动监听成功![" + socketWatch.LocalEndPoint.ToString() + "]";
  72. LogBLL.Err(errinfo);
  73. return true;
  74. }
  75. /// <summary>
  76. /// 监听客户端请求的方法;
  77. /// </summary>
  78. void WatchConnecting()
  79. {
  80. while (true) // 持续不断的监听客户端的连接请求;
  81. {
  82. // 开始监听客户端连接请求,Accept方法会阻断当前的线程;
  83. Socket sokConnection = socketWatch.Accept(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字;
  84. // 将与客户端连接的 套接字 对象添加到集合中;
  85. dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection);
  86. Thread thr = new Thread(ReadSaveFile);
  87. thr.IsBackground = true;
  88. thr.Start(sokConnection);
  89. dictThread.Add(sokConnection.RemoteEndPoint.ToString(), thr); // 将新建的线程 添加 到线程的集合中去。
  90. }
  91. }
  92. public void ReadSaveFile(object clientSocket)
  93. {
  94. Socket client = clientSocket as Socket;
  95. try
  96. {
  97. //client.ReceiveTimeout = 1000 * 150;
  98. //client.SendTimeout = 1000 * 150;
  99. string err = string.Empty;
  100. int alllen = 0;
  101. byte[] datas = ReadData(client, ref alllen, ref err);//待机程序监听到请求
  102. if (datas == null)
  103. {
  104. LogBLL.Err(err);
  105. return;
  106. }
  107. else
  108. {
  109. //byte[] tempstr = new byte[alllen - 32];
  110. //Array.Copy(datas, 32, tempstr, 0, tempstr.Length);
  111. byte[] statusdatas = new byte[4];
  112. Array.Copy(datas, 4, statusdatas, 0, 4);
  113. //Array.Reverse(statusdatas);//20200920
  114. int status = BitConverter.ToInt32(statusdatas, 0);
  115. if (status == 1)//上传
  116. {
  117. byte[] getmd5 = new byte[32];
  118. Array.Copy(datas, 8, getmd5, 0, 32);
  119. string md5 = Encoding.UTF8.GetString(getmd5);
  120. byte[] other = new byte[alllen - 32 - 8];
  121. Array.Copy(datas, 40, other, 0, other.Length);
  122. //DllFileSoc.SocketEntity sockE = null;
  123. int result=SaveToFile(client, md5, other,ref err);
  124. if(result<=0)
  125. LogBLL.Err(err);
  126. }
  127. else if (status == 2)//下载
  128. {
  129. byte[] other = new byte[alllen - 8];
  130. Array.Copy(datas, 8, other, 0, other.Length);
  131. int result = DownToFile(client, other, ref err);
  132. if (result <= 0)
  133. LogBLL.Err(err);
  134. }
  135. else if (status == 5888)//根据机台通信,获取IP、MAC更新数据库机台的RealIP
  136. {
  137. int result = CheckEapRealIP(client, ref err);
  138. if (result <= 0)
  139. LogBLL.Err(err);
  140. }
  141. }
  142. }
  143. catch (Exception ex)
  144. {
  145. LogBLL.Err(ex.Message.ToString());
  146. }
  147. }
  148. private byte[] ReadData(Socket CurrSocket, ref int alllen, ref string errorinfo)
  149. {
  150. byte[] allbuffs = null;
  151. try
  152. {
  153. int zerocount = 0;//等待设置
  154. int levlen = 4;
  155. int result = 0;
  156. byte[] tempbuff = new byte[4];
  157. byte[] bytesbuff = new byte[4];
  158. while (levlen > 0)
  159. {
  160. //说明前面4位还没接受完,需要继续接受
  161. result = CurrSocket.Receive(tempbuff, levlen, SocketFlags.None);//先读取4位块长度字节
  162. if (result == 0 && zerocount <= 20)
  163. {
  164. zerocount++;
  165. //如果返回数据长度为0,则休眠1秒钟,然后继续读取
  166. Thread.Sleep(1000);
  167. continue;
  168. }
  169. if (result <= 0)
  170. {
  171. errorinfo = $"未能从机台上读取数据,可能机台已经断开了,接受长度={result} ";
  172. return null;
  173. }
  174. if (result > 0)
  175. {
  176. Array.Copy(tempbuff, 0, bytesbuff, 4 - levlen, result);
  177. }
  178. levlen = levlen - result;
  179. }
  180. //Array.Reverse(bytesbuff);//20200920
  181. //byte[] alldatas = BitConverter.GetBytes(20122);
  182. //int len11 = BitConverter.ToInt32(alldatas, 0);
  183. //获取总长度
  184. int len = BitConverter.ToInt32(bytesbuff, 0) - 4;
  185. alllen = len;
  186. //if (len > 10)
  187. //{
  188. // int a = 10;
  189. //}
  190. //定义总长度的bytes
  191. byte[] buffs = new byte[len];
  192. tempbuff = new byte[len];
  193. levlen = len;
  194. zerocount = 0;
  195. while (levlen > 0)
  196. {
  197. //说明还没接受完,需要继续接受
  198. result = CurrSocket.Receive(tempbuff, levlen, SocketFlags.None);
  199. //if (result < levlen)
  200. //{
  201. // //添加测试代码
  202. // //int a = 10;
  203. //}
  204. if (result == 0 && zerocount <= 20)
  205. {
  206. zerocount++;
  207. //如果返回数据长度为0,则休眠1秒钟,然后继续读取
  208. Thread.Sleep(1000);
  209. continue;
  210. }
  211. if (result <= 0)
  212. {
  213. errorinfo = $"未能从机台上读取数据,可能机台已经断开了,接受长度={result} ";
  214. return null;
  215. }
  216. if (result > 0)
  217. {
  218. Array.Copy(tempbuff, 0, buffs, len - levlen, result);
  219. }
  220. levlen = levlen - result;
  221. }
  222. //result =mysocket.Receive(buffs,len,SocketFlags.None);
  223. //Array.Reverse(bytesbuff);//20200920
  224. allbuffs = new byte[len + 4];
  225. Array.Copy(bytesbuff, allbuffs, 4);
  226. Array.Copy(buffs, 0, allbuffs, 4, len);
  227. alllen = len + 4;
  228. return allbuffs;
  229. }
  230. catch (SocketException ex)
  231. {
  232. errorinfo = $"Socket接受数据发生异常,错误信息为:" + ex.SocketErrorCode.ToString();
  233. return null;
  234. }
  235. catch (Exception ex)
  236. {
  237. errorinfo = ex.Message.ToString();
  238. errorinfo = $"Socket接受数据发生异常,错误信息为:" + errorinfo;
  239. return null;
  240. }
  241. }
  242. /// <summary>
  243. /// 组成发送包
  244. /// </summary>
  245. /// <param name="mode">1=上传 2=下载</param>
  246. /// <param name="result">1=OK -1=失败 2=文件byte[]传服务器</param>
  247. /// <param name="bf">实体类</param>
  248. /// <returns></returns>
  249. private byte[] GetFileDatas(Int32 mode, Int32 result, BusinessFile bf)
  250. {
  251. byte[] BusinessFilebytes = EntityHelper.SerializeBytes<BusinessFile>(bf);
  252. Int32 len = BusinessFilebytes.Length + 12;
  253. byte[] alldatas = BitConverter.GetBytes(len);
  254. byte[] forAll = (alldatas.Concat(BitConverter.GetBytes(mode)).Concat(BitConverter.GetBytes(result)).Concat(BusinessFilebytes)).ToArray();
  255. return forAll;
  256. }
  257. private byte[] GetFileDatas(Int32 mode, Int32 result, string msg)
  258. {
  259. byte[] msgbytes = Encoding.UTF8.GetBytes(msg);
  260. Int32 len = msgbytes.Length + 12;
  261. byte[] alldatas = BitConverter.GetBytes(len);
  262. byte[] forAll = (alldatas.Concat(BitConverter.GetBytes(mode)).Concat(BitConverter.GetBytes(result)).Concat(msgbytes)).ToArray();
  263. return forAll;
  264. }
  265. private byte[] GetFileDatasMd5(string md5)
  266. {
  267. byte[] msgbytes = Encoding.UTF8.GetBytes(md5);
  268. Int32 len = msgbytes.Length + 4;
  269. byte[] alldatas = BitConverter.GetBytes(len);
  270. byte[] forAll = (alldatas.Concat(msgbytes)).ToArray();
  271. return forAll;
  272. }
  273. private byte[] GetFileDatas(Int32 mode, Int32 result, byte[] files)
  274. {
  275. //byte[] msgbytes = Encoding.UTF8.GetBytes(msg);
  276. Int32 len = files.Length + 12;
  277. byte[] alldatas = BitConverter.GetBytes(len);
  278. byte[] forAll = (alldatas.Concat(BitConverter.GetBytes(mode)).Concat(BitConverter.GetBytes(result)).Concat(files)).ToArray();
  279. return forAll;
  280. }
  281. //private void SaveToFile(Socket client, string md5, byte[] other)
  282. //{
  283. // //FileStream MyFileStream = null;
  284. // //SocketEntity sockE = new SocketEntity();
  285. // IDatabase db = null;
  286. // Dictionary<string, string> dic = new Dictionary<string, string>();
  287. // try
  288. // {
  289. // db = DbFactory.Base("eap");
  290. // db.BeginTrans();
  291. // string str = "";
  292. // //MemoryStream thisms = new MemoryStream(other);
  293. // //sockE = EntityHelper.DeSerializeBytes<SocketEntity>(other);
  294. // // var STR = System.Text.Encoding.UTF8.GetString(other);
  295. // dic = EntityHelper.DeSerializeBytes<Dictionary<string, string>>(other);
  296. // BusinessFile bf = new BusinessFileDal(db).UpdownFileForMd5(md5, dic["fileName"], dic["macCode"], "", "", ref str);
  297. // //BusinessFile bf = new BusinessFileDal(db).UpdownFileForMd5(md5, sockE.FileName, sockE.MacCode, sockE.Remark, sockE.UserId, ref str);
  298. // if (bf != null)//服务器文件已存在,不需要上传
  299. // {
  300. // byte[] datas = GetFileDatas(1, 1, bf);
  301. // client.Send(datas);
  302. // }
  303. // else
  304. // {
  305. // //不存在则上传
  306. // byte[] datas = GetFileDatas(1, 2, "需要上传文件内容");
  307. // //byte[] datas = GetFileDatas(1, 2, bf);
  308. // client.Send(datas);//发送需要上传文件的包
  309. // string err = string.Empty;
  310. // int alllen = 0;
  311. // byte[] afterdatas = ReadData(client, ref alllen, ref err);
  312. // byte[] filebytes = new byte[alllen - 4];
  313. // Array.Copy(afterdatas, 4, filebytes, 0, alllen - 4);
  314. // BusinessFile endbf = new BusinessFileDal(db).UpdownFileForFile(filebytes, dic["fileName"], dic["macCode"], ref str);
  315. // byte[] enddatas = GetFileDatas(1, 1, endbf);
  316. // client.Send(enddatas);//发送上传成功的包
  317. // }
  318. // db.Commit();
  319. // }
  320. // catch (Exception ex)
  321. // {
  322. // db.Rollback();
  323. // LogBLL.Err($"上传文件保存到服务器失败:", ex);
  324. // }
  325. // finally
  326. // {
  327. // if (db != null)
  328. // db.Close();
  329. // }
  330. //}
  331. private int SaveToFile(Socket client, string md5, byte[] other,ref string errorinfo)
  332. {
  333. //FileStream MyFileStream = null;
  334. //SocketEntity sockE = new SocketEntity();
  335. IDatabase db = null;
  336. Dictionary<string, string> dic = new Dictionary<string, string>();
  337. try
  338. {
  339. db = DbFactory.Base("eap");
  340. db.BeginTrans();
  341. string str = "";
  342. //MemoryStream thisms = new MemoryStream(other);
  343. //sockE = EntityHelper.DeSerializeBytes<SocketEntity>(other);
  344. // var STR = System.Text.Encoding.UTF8.GetString(other);
  345. dic = EntityHelper.DeSerializeBytes<Dictionary<string, string>>(other);
  346. BusinessFile bf = new BusinessFileDal(db).UpdownFileForMd5(md5, dic["fileName"], dic["macCode"], "", "", ref str);
  347. //BusinessFile bf = new BusinessFileDal(db).UpdownFileForMd5(md5, sockE.FileName, sockE.MacCode, sockE.Remark, sockE.UserId, ref str);
  348. if (bf != null)//服务器文件已存在,不需要上传
  349. {
  350. byte[] datas = GetFileDatas(1, 1, bf);
  351. client.Send(datas);
  352. return 1;
  353. }
  354. else
  355. {
  356. //不存在则上传
  357. byte[] datas = GetFileDatas(1, 2, "需要上传文件内容");
  358. //byte[] datas = GetFileDatas(1, 2, bf);
  359. client.Send(datas);//发送需要上传文件的包
  360. string err = string.Empty;
  361. int alllen = 0;
  362. byte[] afterdatas = ReadData(client, ref alllen, ref err);
  363. byte[] filebytes = new byte[alllen - 4];
  364. Array.Copy(afterdatas, 4, filebytes, 0, alllen - 4);
  365. BusinessFile endbf = new BusinessFileDal(db).UpdownFileForFile(filebytes, dic["fileName"], dic["macCode"], ref str);
  366. byte[] enddatas = GetFileDatas(1, 1, endbf);
  367. client.Send(enddatas);//发送上传成功的包
  368. }
  369. db.Commit();
  370. return 1;
  371. }
  372. catch (Exception ex)
  373. {
  374. //db.Rollback();
  375. errorinfo = ex.Message.ToString();
  376. return -1;
  377. }
  378. finally
  379. {
  380. if (db != null)
  381. db.Close();
  382. }
  383. }
  384. private int DownToFile(Socket client, byte[] other, ref string errorinfo)
  385. {
  386. //FileStream MyFileStream = null;
  387. //string errinfo = string.Empty;
  388. Dictionary<string, string> dic = new Dictionary<string, string>();
  389. try
  390. {
  391. //string filename = Encoding.UTF8.GetString(file);
  392. //using (MyFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
  393. //{
  394. // long size = MyFileStream.Length;
  395. // byte[] array = new byte[size];
  396. // MyFileStream.Read(array, 0, array.Length);
  397. // MyFileStream.Close();
  398. // byte[] datas = GetFileDatas(2, 1, array);
  399. // //client.Send(datas);
  400. // if (!SendData(client,datas,ref errorinfo))
  401. // {
  402. // return -1;
  403. // }
  404. //}
  405. //return 1;
  406. dic = EntityHelper.DeSerializeBytes<Dictionary<string, string>>(other);
  407. string serverfullpath = dic["serverFullpath"];
  408. string clientMd5 = dic["clientMd5"];
  409. string filename = dic["serverFilename"];
  410. byte[] filedatas = GetDownToFileDatas(client, serverfullpath, ref errorinfo);
  411. byte[] datas = null;
  412. if (filedatas == null)
  413. {
  414. datas = GetFileDatas(2, -1, errorinfo);
  415. }
  416. else
  417. {
  418. if (CheckDownLoadMD5(clientMd5, filedatas, ref errorinfo))//说明客户端有该文件,不需要下载
  419. {
  420. errorinfo = "客户端已存在该文件[" + filename + "],无需下载!";
  421. datas = GetFileDatas(2, 3, errorinfo);
  422. }
  423. else
  424. {
  425. datas = GetFileDatas(2, 1, filedatas);
  426. }
  427. }
  428. if (!SendData(client, datas, ref errorinfo))
  429. {
  430. return -1;
  431. }
  432. return 1;
  433. }
  434. catch (Exception ex)
  435. {
  436. errorinfo = ex.Message.ToString();
  437. return -1;
  438. }
  439. //finally
  440. //{
  441. // if (MyFileStream!=null)
  442. // {
  443. // MyFileStream.Close();
  444. // }
  445. //}
  446. }
  447. /// <summary>
  448. /// 获取当前通信的机台IP、Mac更新EAP机台的realIP
  449. /// </summary>
  450. /// <param name="client"></param>
  451. /// <param name="errorinfo"></param>
  452. /// <returns></returns>
  453. private int CheckEapRealIP(Socket client, ref string errorinfo)
  454. {
  455. try
  456. {
  457. string remoteIP = (client.RemoteEndPoint as IPEndPoint).Address.ToString();
  458. string remoteMAC = ArpTool.GetIpFromMac(remoteIP);
  459. LogBLL.Err("当前建立通信的IP:" + remoteIP + ";MAC地址:" + remoteMAC);
  460. byte[] datas = null;
  461. if (remoteIP.Trim().Length<1 || remoteMAC.Trim().Length<1)
  462. {
  463. errorinfo = "[当前通信异常:缺失IP或MAC]IP:" + remoteIP + ";MAC地址:" + remoteMAC;
  464. datas = GetFileDatas(5888, -1, errorinfo);
  465. }
  466. else
  467. {
  468. Machine mac = new Machine { MacAddress = remoteMAC, RealIP = remoteIP };
  469. if (UpdateRealIP(mac,ref errorinfo)<0)
  470. {
  471. datas = GetFileDatas(5888, -1, errorinfo);
  472. }
  473. else
  474. {
  475. datas = GetFileDatas(5888, 1, errorinfo);
  476. }
  477. }
  478. if (!SendData(client, datas, ref errorinfo))
  479. {
  480. return -1;
  481. }
  482. return 1;
  483. }
  484. catch (Exception ex)
  485. {
  486. errorinfo = ex.Message.ToString();
  487. return -1;
  488. }
  489. }
  490. public int UpdateRealIP(Machine Ma, ref string errorinfo)
  491. {
  492. using (IDatabase db = DbFactory.Base("eap"))
  493. {
  494. db.BeginTrans();
  495. var dal = new MachineDal(db);
  496. int id = dal.UpdateRealIPForMac(Ma,ref errorinfo);
  497. if (id < 0)
  498. {
  499. db.Rollback();
  500. return -1;
  501. }
  502. else
  503. {
  504. db.Commit();
  505. errorinfo = $"根据机台MAC地址:{Ma.MacAddress},更新RealIP:{Ma.RealIP}成功!!!";
  506. }
  507. return 1;
  508. }
  509. }
  510. private bool CheckDownLoadMD5(string clientMd5, byte[] file, ref string errorinfo)
  511. {
  512. try
  513. {
  514. string serverMd5 = GetMD5HashFromFile(file);
  515. if (clientMd5==serverMd5)
  516. {
  517. return true;
  518. }
  519. else
  520. {
  521. return false;
  522. }
  523. }
  524. catch (Exception ex)
  525. {
  526. errorinfo = ex.Message.ToString();
  527. return false;
  528. }
  529. }
  530. private byte[] GetDownToFileDatas(Socket client, string filename, ref string errorinfo)
  531. {
  532. FileStream MyFileStream = null;
  533. //string errinfo = string.Empty;
  534. try
  535. {
  536. //string filename = Encoding.UTF8.GetString(file);
  537. using (MyFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
  538. {
  539. long size = MyFileStream.Length;
  540. byte[] array = new byte[size];
  541. MyFileStream.Read(array, 0, array.Length);
  542. MyFileStream.Close();
  543. //byte[] datas = GetFileDatas(2, 1, array);
  544. //return datas;
  545. return array;
  546. }
  547. }
  548. catch (Exception ex)
  549. {
  550. errorinfo = ex.Message.ToString();
  551. return null;
  552. }
  553. finally
  554. {
  555. if (MyFileStream != null)
  556. {
  557. MyFileStream.Close();
  558. }
  559. }
  560. }
  561. private bool SendData(Socket CurrSocket, byte[] allbytes, ref string errorinfo)
  562. {
  563. try
  564. {
  565. //包的大小 1MB
  566. int PacketSize = 1024*1024;
  567. //包的数量
  568. int PacketCount = (int)(allbytes.Length / ((long)PacketSize));
  569. //最后一个包的大小
  570. int LastDataPacket = (int)(allbytes.Length - ((long)(PacketSize * PacketCount)));
  571. int satrtNum = 1;
  572. int len = PacketCount;
  573. byte[] sendArr = null;
  574. while (len > 0)
  575. {
  576. sendArr = new byte[PacketSize];
  577. Array.Copy(allbytes, (satrtNum - 1) * PacketSize, sendArr, 0, PacketSize);
  578. //CurrSocket.Send(sendArr);//发送文件内容
  579. if (!SendDataIt(CurrSocket, sendArr, ref errorinfo))
  580. return false;
  581. len = len - 1;
  582. satrtNum++;
  583. }
  584. if (LastDataPacket != 0)
  585. {
  586. sendArr = new byte[LastDataPacket];
  587. Array.Copy(allbytes, PacketCount * PacketSize, sendArr, 0, LastDataPacket);
  588. //CurrSocket.Send(sendArr);//发送最后一个包
  589. if (!SendDataIt(CurrSocket, sendArr, ref errorinfo))
  590. return false;
  591. }
  592. return true;
  593. }
  594. catch (SocketException ex)
  595. {
  596. errorinfo = "Socket发送数据发生异常,错误信息为:" + ex.SocketErrorCode.ToString();
  597. return false;
  598. }
  599. catch (Exception ex)
  600. {
  601. errorinfo = ex.Message.ToString();
  602. errorinfo = "Socket发送数据发生异常,错误信息为:" + errorinfo;
  603. return false;
  604. }
  605. }
  606. private bool SendDataIt(Socket CurrSocket, byte[] allbytes, ref string errorinfo)
  607. {
  608. try
  609. {
  610. int lenlev = allbytes.Length;
  611. byte[] tempbytes = null;
  612. int result = 0;
  613. while (lenlev > 0)
  614. {
  615. tempbytes = new byte[lenlev];
  616. Array.Copy(allbytes, allbytes.Length - lenlev, tempbytes, 0, lenlev);
  617. result = CurrSocket.Send(tempbytes);//发送文件内容
  618. lenlev = lenlev - result;
  619. }
  620. return true;
  621. }
  622. catch (SocketException ex)
  623. {
  624. errorinfo = "Socket发送数据发生异常,错误信息为:" + ex.SocketErrorCode.ToString();
  625. return false;
  626. }
  627. catch (Exception ex)
  628. {
  629. errorinfo = ex.Message.ToString();
  630. errorinfo = "Socket发送数据发生异常,错误信息为:" + errorinfo;
  631. return false;
  632. }
  633. }
  634. public bool Close(ref string errinfo)
  635. {
  636. return ShutDownSocket(socketWatch, ref errinfo);
  637. }
  638. static void ShutDownSocket(Socket sk, FileStream fs)
  639. {
  640. if (sk != null)
  641. {
  642. sk.Close(); //关闭套接字
  643. }
  644. if (fs != null)
  645. {
  646. fs.Close();//关闭文件流
  647. }
  648. }
  649. //关闭连接
  650. public bool ShutDownSocket(Socket sk, ref string errinfo)
  651. {
  652. try
  653. {
  654. if (sk == null)
  655. {
  656. return true;
  657. }
  658. else
  659. {
  660. sk.Close();//关闭Socket
  661. sk = null;
  662. return true;
  663. }
  664. }
  665. catch (Exception ex)
  666. {
  667. sk = null;
  668. errinfo += ex.Message;
  669. return false;
  670. }
  671. }
  672. /// <summary>
  673. /// 获取当前IPV4地址
  674. /// </summary>
  675. /// <returns></returns>
  676. public string getEapIpv4()
  677. {
  678. string ipv4 = "";
  679. string name = Dns.GetHostName();
  680. IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
  681. foreach (IPAddress ipa in ipadrlist)
  682. {
  683. if (ipa.AddressFamily == AddressFamily.InterNetwork)
  684. {
  685. ipv4 = ipa.ToString();
  686. break;
  687. }
  688. }
  689. return ipv4;
  690. }
  691. public static string GetMD5HashFromFile(byte[] filedatas)
  692. {
  693. try
  694. {
  695. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  696. byte[] retVal = md5.ComputeHash(filedatas);
  697. StringBuilder sb = new StringBuilder();
  698. for (int i = 0; i < retVal.Length; i++)
  699. {
  700. sb.Append(retVal[i].ToString("x2"));
  701. }
  702. return sb.ToString();
  703. }
  704. catch (Exception ex)
  705. {
  706. //errorinfo = ex.Message.ToString();
  707. return "";
  708. }
  709. }
  710. }
  711. }