SocketManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using System.Windows.Forms;
  7. using System.Text;
  8. using HardwareConfig;
  9. using BaseLibRWFile;
  10. namespace BaseLibComm
  11. {
  12. public struct StNetworkPort
  13. {
  14. public int Index;
  15. public bool Enable;
  16. public string Name;
  17. public string IP;
  18. public string Port;
  19. public Socket[] ArrSocket;
  20. public bool[] ArrLinkStatus;
  21. public string[] ArrStrRecMsg;
  22. }
  23. public class SocketManager
  24. {
  25. public static SocketManager Ins { set; get; } = new SocketManager();
  26. public static Dictionary<string, StNetworkPort> DicSeverStruct { set; get; } = new Dictionary<string, StNetworkPort> { };
  27. public static Dictionary<string, StNetworkPort> DicClientStruct { set; get; } = new Dictionary<string, StNetworkPort> { };
  28. public SocketManager()
  29. {
  30. }
  31. public Ini newIni;
  32. public static List<SocketAtti> listSocketAttisServer = new List<SocketAtti>();
  33. public static List<SocketAtti> listSocketAttisClient = new List<SocketAtti>();
  34. public void LoadServerClient()
  35. {
  36. listSocketAttisServer.Clear();
  37. listSocketAttisClient.Clear();
  38. newIni = new Ini(Application.StartupPath + "\\Vision\\Config\\Net.ini");
  39. int iServerCount = Convert.ToInt32(newIni.ReadIni("Count", "服务器数量", "1"));
  40. int iClientCount = Convert.ToInt32(newIni.ReadIni("Count", "客户端数量", "1"));
  41. for (int i = 0; i < iServerCount; i++)
  42. {
  43. SocketAtti socketAtti = new SocketAtti
  44. {
  45. 编号 = i,
  46. 网口类型 = SocketTypeEnum.服务器,
  47. 网口名称 = newIni.ReadIni($"服务器{i}", "名称", $"服务器{i}"),
  48. Enable = Convert.ToBoolean(newIni.ReadIni($"服务器{i}", "Enable", "False")),
  49. IP = newIni.ReadIni($"服务器{i}", "IP", "127.0.0.1"),
  50. 端口号 = newIni.ReadIni($"服务器{i}", "端口号", "8000")
  51. };
  52. listSocketAttisServer.Add(socketAtti);
  53. }
  54. for (int i = 0; i < iClientCount; i++)
  55. {
  56. SocketAtti socketAtti = new SocketAtti
  57. {
  58. 编号 = i,
  59. 网口类型 = SocketTypeEnum.客户端,
  60. 网口名称 = newIni.ReadIni($"客户端{i}", "名称", $"客户端{i}"),
  61. Enable = Convert.ToBoolean(newIni.ReadIni($"客户端{i}", "Enable", "False")),
  62. IP = newIni.ReadIni($"客户端{i}", "IP", "127.0.0.1"),
  63. 端口号 = newIni.ReadIni($"客户端{i}", "端口号", "8000")
  64. };
  65. listSocketAttisClient.Add(socketAtti);
  66. }
  67. }
  68. public void LoadSocket()
  69. {
  70. LoadServerClient();
  71. StNetworkPort st = new StNetworkPort();
  72. foreach (var p in listSocketAttisServer)//var p in HardConfigManager.Ins.HardwareList
  73. {
  74. st.Index = p.编号;
  75. st.IP = p.IP;
  76. st.Name = p.网口名称;
  77. st.Port = p.端口号;
  78. st.ArrStrRecMsg = new string[20];
  79. st.ArrLinkStatus = new bool[20];
  80. st.ArrSocket = new Socket[20];
  81. DicSeverStruct.Add(st.Name, st);
  82. }
  83. foreach (var p in listSocketAttisClient)
  84. {
  85. st.Index = p.编号;
  86. st.IP = p.IP;
  87. st.Name = p.网口名称;
  88. st.Port = p.端口号;
  89. st.ArrStrRecMsg = new string[1];
  90. st.ArrLinkStatus = new bool[1];
  91. st.ArrSocket = new Socket[1];
  92. DicClientStruct.Add(st.Name, st);
  93. }
  94. #region MyRegion
  95. //if (p.Enable)
  96. //{
  97. //switch (p.网口类型)//p.HardwareName
  98. //{
  99. // SocketAtti sockethc = (SocketAtti)p;
  100. // st.Index = sockethc.编号;
  101. // st.IP = sockethc.IP;
  102. // st.Name = sockethc.网口名称;
  103. // st.Port = sockethc.端口号;
  104. // if (sockethc.网口类型==SocketTypeEnum.客户端)
  105. // {
  106. // st.ArrStrRecMsg = new string[1];
  107. // st.ArrLinkStatus = new bool[1];
  108. // st.ArrSocket = new Socket[1];
  109. // DicClientStruct.Add(st.Name, st);
  110. // }
  111. // else if (sockethc.网口类型 == SocketTypeEnum.服务器)
  112. // {
  113. // st.ArrStrRecMsg = new string[20];
  114. // st.ArrLinkStatus = new bool[20];
  115. // st.ArrSocket = new Socket[20];
  116. // DicClientStruct.Add(st.Name, st);
  117. // }
  118. // break;
  119. //default:
  120. // break;
  121. //}
  122. //}
  123. #endregion
  124. }
  125. public bool CreatSocket()
  126. {
  127. int ret = 0;
  128. foreach (var p in DicSeverStruct)
  129. {
  130. if (!p.Value.ArrLinkStatus[0] && p.Value.Name!="UIServer")
  131. {
  132. if (!CreateServer(p.Value))
  133. {
  134. ret--;
  135. //return false;
  136. }
  137. }
  138. }
  139. try
  140. {
  141. foreach (var p in DicClientStruct)
  142. {
  143. if (!p.Value.ArrLinkStatus[0] && p.Value.Name != "UIClient")
  144. {
  145. if (!CreateClient(p.Value))
  146. {
  147. ret--;
  148. //return false;
  149. }
  150. }
  151. }
  152. }
  153. catch (Exception ex)
  154. {
  155. MessageBox.Show("创建客户端错误 " + ex.Message);
  156. }
  157. if (ret == 0)
  158. {
  159. return true;
  160. }
  161. return false;
  162. }
  163. public bool CreateServer(StNetworkPort st)
  164. {
  165. try
  166. {
  167. if (st.ArrSocket[0] == null)
  168. {
  169. st.ArrSocket[0] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  170. IPAddress address = IPAddress.Parse(st.IP);
  171. IPEndPoint point = new IPEndPoint(address, int.Parse(st.Port));
  172. st.ArrSocket[0].Bind(point);
  173. st.ArrSocket[0].Listen(20);
  174. st.ArrLinkStatus[0] = true;
  175. if (!DicSeverStruct.ContainsKey($"{st.Name}"))
  176. {
  177. //DicSeverStruct.Remove($"{st.Name}");
  178. DicSeverStruct.Add($"{st.Name}", st);
  179. }
  180. Thread ServerLisenThread = new Thread(new ParameterizedThreadStart(ServerLisening));
  181. ServerLisenThread.IsBackground = true;
  182. ServerLisenThread.Start($"{st.Name}");
  183. return true;
  184. }
  185. else
  186. {
  187. MessageBox.Show($"服务器{st.IP}:{st.Port}已创建\r\nServer {st.IP}:{st.Port} created");
  188. return false;
  189. }
  190. }
  191. catch (Exception ex)
  192. {
  193. MessageBox.Show($"创建服务器{st.IP}:{st.Port}失败\r\nCreate {st.IP}:{st.Port} failed\r\n{ex.Message}");
  194. return false;
  195. }
  196. }
  197. private void ServerLisening(object structName)
  198. {
  199. string stName = structName as string;
  200. int indexClient = 0;
  201. Socket s = null;
  202. while (true)
  203. {
  204. try
  205. {
  206. indexClient++;
  207. if (indexClient > 19)
  208. {
  209. indexClient = 1;
  210. }
  211. if (DicSeverStruct[stName].ArrSocket[indexClient] == null)
  212. {
  213. DicSeverStruct[stName].ArrSocket[indexClient] = DicSeverStruct[stName].ArrSocket[0].Accept();
  214. s = DicSeverStruct[stName].ArrSocket[indexClient];
  215. }
  216. }
  217. catch (Exception ex)
  218. {
  219. DicSeverStruct[stName].ArrLinkStatus[0] = false;
  220. DicSeverStruct[stName].ArrStrRecMsg[0] = string.Empty;
  221. DicSeverStruct[stName].ArrSocket[0] = null;
  222. MessageBox.Show($"监听服务器{DicSeverStruct[stName].IP}:{DicSeverStruct[stName].Port}出错" +
  223. $"\r\nLisening server{DicSeverStruct[stName].IP}:{DicSeverStruct[stName].Port} error\r\n{ex.Message}");
  224. break;
  225. }
  226. if (s != null)
  227. {
  228. IPAddress clientIP = (s.RemoteEndPoint as IPEndPoint).Address;
  229. int clientPort = (s.RemoteEndPoint as IPEndPoint).Port;
  230. string sendmsg = $"连接服务端成功!本地IP:{clientIP},本地端口:{clientPort}";
  231. byte[] arrSendMsg = Encoding.Default.GetBytes(sendmsg);
  232. s.Send(arrSendMsg);
  233. string remoteEndPoint = $"{s.LocalEndPoint}_{s.RemoteEndPoint}";
  234. IPEndPoint netpoint = s.RemoteEndPoint as IPEndPoint;
  235. Thread thread = new Thread(new ParameterizedThreadStart(ServerReceive));
  236. thread.IsBackground = true;
  237. thread.Start($"{stName},{indexClient}");
  238. DicSeverStruct[stName].ArrLinkStatus[indexClient] = true;
  239. }
  240. Thread.Sleep(1);
  241. }
  242. }
  243. private void ServerReceive(object structName)
  244. {
  245. string stNameI = structName as string;
  246. string stName = stNameI.Split(',')[0];
  247. int indexClient = Convert.ToInt32(stNameI.Split(',')[1]);
  248. Socket s = DicSeverStruct[stName].ArrSocket[indexClient];
  249. int keepAlive = -1744830460; // SIO_KEEPALIVE_VALS
  250. //KeepAlive的时间为20秒,检查间隔为2秒,20秒的16进制表示是4e20,2秒的16进制表示是07d0
  251. byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };
  252. s.IOControl(keepAlive, inValue, null);
  253. while (true)
  254. {
  255. try
  256. {
  257. if (CheckConnectStatus(s))
  258. {
  259. if (s.Available != 0)
  260. {
  261. byte[] recBytes = new byte[1024 * 8];
  262. int length = 1;
  263. while (length > 0)
  264. {
  265. length = s.Receive(recBytes);
  266. DicSeverStruct[stName].ArrStrRecMsg[indexClient] += Encoding.Default.GetString(recBytes, 0, length);
  267. }
  268. }
  269. }
  270. else
  271. {
  272. DicSeverStruct[stName].ArrLinkStatus[indexClient] = false;
  273. DicSeverStruct[stName].ArrStrRecMsg[indexClient] = string.Empty;
  274. DicSeverStruct[stName].ArrSocket[indexClient] = null;
  275. //SeverStructDic.Remove(stName);
  276. //MessageBox.Show($"客户端{stName}已经中断连接\r\nClient{stName} disconnect");
  277. string str = $"客户端{stName}已经中断连接:";
  278. Msg.Show($"{str}\r\n", $"{str}\r\nThe client has disconnected:\r\n",
  279. $"{str}\r\nKhách hàng đã ngắt kết nối:\r\n","Error", msgicon: MessageBoxIcon.Error);
  280. break;
  281. }
  282. }
  283. catch (Exception ex)
  284. {
  285. DicSeverStruct[stName].ArrLinkStatus[indexClient] = false;
  286. DicSeverStruct[stName].ArrStrRecMsg[indexClient] = string.Empty;
  287. DicSeverStruct[stName].ArrSocket[indexClient] = null;
  288. //SeverStructDic.Remove(stName);
  289. //MessageBox.Show($"客户端{stName}已经中断连接\r\nClient{stName} disconnect\r\n{ex.Message}");
  290. string str = $"客户端{stName}已经中断连接:";
  291. Msg.Show($"{str}\r\n{ex}", $"{str}\r\nThe client has disconnected:\r\n{ex}",
  292. $"{str}\r\nKhách hàng đã ngắt kết nối:\r\n{ex}","Error", msgicon: MessageBoxIcon.Error);
  293. break;
  294. }
  295. Thread.Sleep(1);
  296. }
  297. }
  298. public bool CreateClient(StNetworkPort st)
  299. {
  300. try
  301. {
  302. IPAddress IP1 = IPAddress.Parse(st.IP);
  303. IPEndPoint remoteEP = new IPEndPoint(IP1, int.Parse(st.Port));
  304. st.ArrSocket[0] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  305. st.ArrSocket[0].Connect(remoteEP);
  306. st.ArrLinkStatus[0] = true;
  307. if (!DicClientStruct.ContainsKey($"{st.Name}"))
  308. {
  309. //DicClientStruct.Remove($"{st.Name}");
  310. DicClientStruct.Add($"{st.Name}", st);
  311. }
  312. Thread ClientReceiveThread = new Thread(new ParameterizedThreadStart(ReceiveData));
  313. ClientReceiveThread.IsBackground = true;
  314. ClientReceiveThread.Start($"{st.Name}");
  315. return true;
  316. }
  317. catch (Exception ex)
  318. {
  319. st.ArrLinkStatus[0] = false;
  320. if (!DicClientStruct.ContainsKey($"{st.Name}"))
  321. {
  322. //DicClientStruct.Remove($"{st.Name}");
  323. DicClientStruct.Add($"{st.Name}", st);
  324. }
  325. string str = $"{st.Name}连接服务器{st.IP}:{st.Port}失败";
  326. Msg.Show($"{str}\r\n{ex}", $"{str}\r\nFailed to link to server:\r\n{ex}",
  327. $"{str}\r\nkết nối thất bại:\r\n{ex}", "Error", msgicon: MessageBoxIcon.Error);
  328. //MessageBox.Show($"{st.Name}连接服务器{st.IP}:{st.Port}失败\r\n{st.Name}Connect sever {st.IP}:{st.Port} failed\r\n{ex.Message}");
  329. return false;
  330. }
  331. }
  332. public void ReceiveData(object structName)
  333. {
  334. string stName = structName as string;
  335. Socket s = DicClientStruct[stName].ArrSocket[0];
  336. while (true)
  337. {
  338. try
  339. {
  340. if (CheckConnectStatus(s))
  341. {
  342. if (s.Available != 0)
  343. {
  344. byte[] recBytes = new byte[1024 * 8];
  345. int length = 1;
  346. while (s.Available != 0)
  347. {
  348. length = s.Receive(recBytes);
  349. DicClientStruct[stName].ArrStrRecMsg[0] += Encoding.Default.GetString(recBytes, 0, length);
  350. }
  351. }
  352. }
  353. else
  354. {
  355. DicClientStruct[stName].ArrLinkStatus[0] = false;
  356. DicClientStruct[stName].ArrStrRecMsg[0] = string.Empty;
  357. DicClientStruct[stName].ArrSocket[0] = null;
  358. //ClientStructDic.Remove(stName);
  359. //MessageBox.Show($"{stName}已经中断连接\r\n{stName} disconnect");
  360. string str = $"{stName}客户端已经中断连接:";
  361. Msg.Show($"{str}\r\n", $"{str}\r\nThe client has disconnected:\r\n",
  362. $"{str}\r\nKhách hàng đã ngắt kết nối:\r\n","Error", msgicon: MessageBoxIcon.Error);
  363. break;
  364. }
  365. }
  366. catch (Exception ex)
  367. {
  368. DicClientStruct[stName].ArrLinkStatus[0] = false;
  369. DicClientStruct[stName].ArrStrRecMsg[0] = string.Empty;
  370. DicClientStruct[stName].ArrSocket[0] = null;
  371. //ClientStructDic.Remove(stName);
  372. //MessageBox.Show($"{stName}已经中断连接\r\n{stName} disconnect\r\n{ex.Message}");
  373. string str = $"{stName}客户端已经中断连接";
  374. Msg.Show($"{str}\r\n{ex}", $"{str}\r\nThe client has disconnected:\r\n{ex}",
  375. $"{str}\r\nKhách hàng đã ngắt kết nối:\r\n{ex}","Error", msgicon: MessageBoxIcon.Error);
  376. break;
  377. }
  378. Thread.Sleep(1);
  379. }
  380. }
  381. public bool SendData(Socket s, string sendStr, bool Is16)
  382. {
  383. try
  384. {
  385. if (CheckConnectStatus(s))
  386. {
  387. byte[] sendBytes;
  388. if (Is16)
  389. {
  390. sendBytes = HexStrTobyte(sendStr);
  391. }
  392. else
  393. {
  394. sendBytes = Encoding.UTF8.GetBytes(sendStr);
  395. }
  396. int testNum = s.Send(sendBytes);
  397. return true;
  398. }
  399. return false;
  400. }
  401. catch (Exception ex)
  402. {
  403. MessageBox.Show(ex.Message);
  404. return false;
  405. }
  406. }
  407. private byte[] HexStrTobyte(string hexString)
  408. {
  409. hexString = hexString.Replace(" ", "");
  410. if (hexString.Length % 2 != 0)
  411. hexString += " ";
  412. byte[] returnBytes = new byte[hexString.Length / 2];
  413. for (int i = 0; i < returnBytes.Length; i++)
  414. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
  415. return returnBytes;
  416. }
  417. // 字节数组转16进制字符串
  418. public string byteToHexStr(byte[] bytes)
  419. {
  420. string returnStr = "";
  421. if (bytes != null)
  422. {
  423. for (int i = 0; i < bytes.Length; i++)
  424. {
  425. returnStr += bytes[i].ToString("X2");//ToString("X2") 为C#中的字符串格式控制符
  426. }
  427. }
  428. return returnStr;
  429. }
  430. public byte[] HexStringToBytes(string hs)
  431. {
  432. string[] strArr = hs.Trim().Split(' ');
  433. byte[] b = new byte[strArr.Length];
  434. //逐个字符变为16进制字节数据
  435. for (int i = 0; i < strArr.Length; i++)
  436. {
  437. b[i] = Convert.ToByte(strArr[i], 16);
  438. }
  439. //按照指定编码将字节数组变为字符串
  440. return b;
  441. }
  442. public string ReceiveSocketData(Socket s)
  443. {
  444. if (CheckConnectStatus(s))
  445. {
  446. string strTemp = "";
  447. if (!(s.Available == 0))
  448. {
  449. byte[] recBytes = new byte[s.Available];
  450. int lengh = s.Receive(recBytes);
  451. strTemp = Encoding.Default.GetString(recBytes, 0, lengh);
  452. }
  453. if (strTemp.Length > 0)
  454. {
  455. return strTemp;
  456. }
  457. }
  458. return "";
  459. }
  460. /// <summary>
  461. /// 增加链接次数 次数很多未链接 则跳出循环
  462. /// </summary>
  463. /// <param name="socketpara"></param>
  464. public string ByteToString(byte[] recBytes)
  465. {
  466. string strTemp = "";
  467. for (int i = 9; i < 13; i++)
  468. {
  469. strTemp += recBytes[i].ToString("X2"); //((char)recBytes[i]).ToString();//
  470. }
  471. if (!string.IsNullOrEmpty(strTemp))
  472. {
  473. strTemp = _16ToA(strTemp);
  474. string alpha = ((char)int.Parse(strTemp)).ToString();
  475. return alpha;
  476. }
  477. return null;
  478. }
  479. /// <summary>
  480. /// 16进制字符串转换为Ascii字符串
  481. /// 有些不需要的字符可以加判断清除
  482. /// </summary>
  483. /// <param name="InHex">16进制字符串</param>
  484. /// <returns>Ascii字符串</returns>
  485. public string _16ToA(string InHex)
  486. {
  487. int a = InHex.Length;
  488. string str1 = "";
  489. string str = "";
  490. byte[] MMid = new byte[a];
  491. for (int z = 0; z < a / 2; z++)
  492. {
  493. str1 = InHex.Substring(z * 2, 2);
  494. MMid[z] = Convert.ToByte(str1, 16);
  495. if (MMid[z] < 0x1f)//判断清除不可见字符
  496. {
  497. MMid[z] = 0x00;
  498. }
  499. string aa = MMid[z].ToString("X2");
  500. }
  501. str = Encoding.ASCII.GetString(MMid);
  502. //Console.Write(str);
  503. return str;
  504. }
  505. public bool CheckConnectStatus(Socket s) //检查连接状态
  506. {
  507. if (s == null)
  508. {
  509. return false;
  510. }
  511. bool ConnectStatus = !(s.Poll(1000, SelectMode.SelectRead) && s.Available == 0 || !s.Connected);
  512. return ConnectStatus;
  513. }
  514. public void SocketClose(Socket socket)
  515. {
  516. if (socket == null)
  517. return;
  518. //if (!socket.Connected)
  519. // return;
  520. try
  521. {
  522. socket.Shutdown(SocketShutdown.Both);
  523. }
  524. catch
  525. {
  526. }
  527. try
  528. {
  529. socket.Close();
  530. }
  531. catch
  532. {
  533. }
  534. }
  535. }
  536. }