UDPCommunication.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net;
  7. using System.Threading;
  8. using System.Text.RegularExpressions;
  9. using System.Xml;
  10. using System.IO;
  11. using AGV_WPF_Global;
  12. namespace Services
  13. {
  14. public class UdpCommunication : CommunicationBase
  15. {
  16. private string localIP;
  17. byte[] buf_traffic = { 0x10, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x03 };
  18. private string str1061 = "";
  19. public string LocalIP
  20. {
  21. get
  22. {
  23. if (string.IsNullOrEmpty(localIP))
  24. {
  25. return Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
  26. }
  27. return localIP;
  28. }
  29. set
  30. {
  31. string str = @"^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$";
  32. if (Regex.IsMatch(value, str))
  33. {
  34. localIP = value;
  35. }
  36. else
  37. {
  38. throw new Exception("IP地址格式错误");
  39. }
  40. }
  41. }
  42. private int port;
  43. public int Port
  44. {
  45. get
  46. {
  47. if (port <= 0)
  48. return 10000;
  49. return port;
  50. }
  51. set { port = value; }
  52. }
  53. private int scanTime;
  54. public int ScanTime
  55. {
  56. get
  57. {
  58. if (scanTime <= 0)
  59. return 10;
  60. return scanTime;
  61. }
  62. set { scanTime = value; }
  63. }
  64. public override object GetTag()
  65. {
  66. return this;
  67. }
  68. private UdpClient udpServer;
  69. private Thread thread;
  70. public UdpCommunication(string ip, int port, int scanTime = 0)
  71. {
  72. LocalIP = ip;
  73. Port = port;
  74. ScanTime = scanTime;
  75. //InitIPConfig();
  76. IsOpen = false;
  77. str1061 = ByteToHexString(buf_traffic);
  78. }
  79. AutoResetEvent done = new AutoResetEvent(true);
  80. public static string ByteToHexString(byte[] buffer)
  81. {
  82. StringBuilder builder = new StringBuilder(buffer.Length * 3);
  83. foreach (byte data in buffer)
  84. {
  85. builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
  86. }
  87. return builder.ToString().ToUpper();
  88. }
  89. bool isChange = false;
  90. /// <summary>
  91. /// 网络接收线程
  92. /// </summary>
  93. private void ReceiveThread()
  94. {
  95. IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
  96. //开始循环监听
  97. while (true)
  98. {
  99. if (IsOpen && udpServer != null)
  100. {
  101. ReceivedEventArgs e = new ReceivedEventArgs();
  102. try
  103. {
  104. // e.buffer = udpServer.Receive(ref remotePoint);//接收数据
  105. var resultAny = udpServer.BeginReceive(null, null);
  106. e.buffer = udpServer.EndReceive(resultAny, ref remotePoint);
  107. e.type = "UDP";
  108. if (isChange)
  109. {
  110. Console.ForegroundColor = ConsoleColor.Yellow;
  111. isChange = false;
  112. }
  113. else
  114. {
  115. Console.ForegroundColor = ConsoleColor.Green;
  116. isChange = true;
  117. }
  118. if (remotePoint.Address.ToString() != LocalIP)//如果为本机IP,则不触发接收事件
  119. {
  120. //if(e.buffer.Count()>=10)
  121. //{
  122. if (e.buffer!=null&&ByteToHexString(e.buffer) != str1061&&e.buffer.Length>10)
  123. {
  124. base.OnReceivedEvent(remotePoint, e);
  125. }
  126. }
  127. }
  128. catch (System.Exception ex)
  129. {
  130. }
  131. }
  132. }
  133. }
  134. private List<string> IpBuffer = new List<string>();
  135. private static object portLock = new object();
  136. private static object portLock2 = new object();
  137. void WriteFile(string fileName, string context)
  138. {
  139. try
  140. {
  141. lock (portLock)
  142. {
  143. DateTime time = DateTime.Now;
  144. //MessageBox.Show("线程异常:"+e.ExceptionObject);
  145. FileStream stream = File.Open(@"Exception\" + fileName + ".txt", FileMode.Append, FileAccess.Write);
  146. StreamWriter writer = new StreamWriter(stream);
  147. {
  148. string msg = string.Format("[{0}]Test:\r\nMessage:{1}\r\n", time.ToString("yyyy-MM-dd HH:mm:ss"), context);
  149. writer.WriteLine(msg);
  150. writer.Close();
  151. stream.Close();
  152. }
  153. }
  154. }
  155. catch (Exception)
  156. {
  157. }
  158. }
  159. string Str1063 = "";
  160. /// <summary>
  161. /// 发送数据给AGV车辆
  162. /// </summary>
  163. /// <param name="buffer"></param>
  164. /// <param name="o"></param>
  165. public override void SendData(byte[] buffer, object o)
  166. {
  167. IPEndPoint ip = o as IPEndPoint;
  168. if (ip == null)
  169. {
  170. string ipStr = LocalIP.Substring(0, LocalIP.LastIndexOf('.') + 1);
  171. try
  172. {
  173. if (IsOpen && buffer != null && buffer.Length > 0)
  174. {
  175. //string msg = string.Format("[{0,-15}:{1} {2}]发送:{3}", LocalIP, Port, DateTime.Now.ToString("HH:mm:ss.fff"), ByteToHexString(buffer));
  176. //Console.WriteLine(msg);
  177. // lock (portLock2)
  178. {
  179. if (buffer[0] == 0x10 && (buffer[1] == 0x61 || buffer[1] == 0x63))
  180. {
  181. if (GlobalPara.Gloal1063Flag)
  182. {
  183. if (Str1063 != UdpCommunication.ByteToHexString(buffer))
  184. {
  185. Str1063 = UdpCommunication.ByteToHexString(buffer);
  186. WriteFile("1061发送记录-" + DateTime.Now.ToString("yyyy-MM-dd"), Str1063);
  187. }
  188. }
  189. }
  190. {
  191. // udpServer.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(ipStr + "255"), Port));
  192. }
  193. }
  194. foreach (var ipstr in IpBuffer)
  195. {
  196. if (IPCheck(ipstr))
  197. {
  198. udpServer.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(ipstr), Port));
  199. }
  200. }
  201. Thread.Sleep(20);
  202. }
  203. }
  204. catch (System.Exception ex)
  205. {
  206. }
  207. }
  208. else
  209. {
  210. try
  211. {
  212. if (IsOpen)
  213. {
  214. Console.WriteLine(string.Format("[{0,-15}:{1} {2}]发送:{3}", LocalIP, Port, DateTime.Now.ToString("HH:mm:ss"), ByteToHexString(buffer)));
  215. udpServer.Send(buffer, buffer.Length, new IPEndPoint(ip.Address, Port));
  216. }
  217. }
  218. catch (System.Exception ex)
  219. {
  220. }
  221. }
  222. }
  223. /// <summary>
  224. /// 关闭通讯服务器连接
  225. /// </summary>
  226. public override void Close()
  227. {
  228. if (udpServer != null)
  229. {
  230. udpServer.Close();
  231. udpServer = null;
  232. }
  233. if (thread != null && thread.ThreadState != ThreadState.Stopped)
  234. {
  235. if (done.WaitOne(500))
  236. {
  237. //thread.Resume();
  238. thread.Abort();
  239. }
  240. thread = null;
  241. }
  242. IsOpen = false;
  243. }
  244. /// <summary>
  245. /// 释放资源
  246. /// </summary>
  247. public override void Dispose()
  248. {
  249. if (udpServer != null)
  250. udpServer.Close();
  251. if (thread != null && thread.ThreadState != ThreadState.Stopped)
  252. {
  253. if (done.WaitOne(500))
  254. {
  255. thread.Abort();
  256. }
  257. thread.Abort();
  258. thread = null;
  259. }
  260. base.Dispose();
  261. }
  262. /// <summary>
  263. /// 打开通讯服务器连接端口
  264. /// </summary>
  265. public override void Open()
  266. {
  267. if (thread != null && udpServer != null)
  268. {
  269. if (thread.ThreadState == ThreadState.Suspended)
  270. {
  271. thread.Resume();
  272. }
  273. else if (thread.ThreadState == ThreadState.Unstarted)
  274. {
  275. thread.Start();
  276. }
  277. }
  278. else
  279. {
  280. IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName());
  281. for (int i = 0; i < address.Count(); i++)
  282. {
  283. if (address[i].AddressFamily.ToString().ToLower() == "internetwork" && address[i].ToString() == LocalIP)
  284. {
  285. udpServer = new UdpClient(new IPEndPoint(IPAddress.Parse(LocalIP), Port));
  286. udpServer.Client.ReceiveTimeout = 500;
  287. udpServer.Client.SendTimeout = 500;
  288. thread = new Thread(ReceiveThread);
  289. thread.IsBackground = true;
  290. thread.Start();
  291. break;
  292. }
  293. else if (i == address.Count() - 1)
  294. {
  295. //MessageBox.Show("IP地址不存在");
  296. //throw new Exception("UDP中IP地址不存在");
  297. Console.WriteLine("UDP中IP地址不存在");
  298. return;
  299. }
  300. }
  301. }
  302. IsOpen = true;
  303. InitIPConfig();
  304. }
  305. private void InitIPConfig()
  306. {
  307. XmlDocument xmlDoc = new XmlDocument();
  308. xmlDoc.Load("IPAddress.xml");
  309. XmlNode xn = xmlDoc.SelectSingleNode("AGVS");//根节点
  310. XmlNodeList nodeList = xn.ChildNodes;//根节点下面的子节点
  311. foreach (XmlNode xnf in nodeList)//遍历所有子节点
  312. {
  313. XmlElement xe = (XmlElement)xnf;
  314. string AgvId = xe.ChildNodes[0].InnerText;//agv编号
  315. XmlNodeList ipList = xe.ChildNodes[1].ChildNodes;
  316. foreach (XmlNode ip in ipList)
  317. {
  318. XmlElement ipxe = (XmlElement)ip;
  319. string ipStr = ip.InnerText;//IP地址
  320. if (IPCheck(ipStr))
  321. {
  322. if (!IpBuffer.Contains(ipStr))
  323. {
  324. IpBuffer.Add(ipStr);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. public bool IPCheck(string ipAddress)
  331. {
  332. if (string.IsNullOrEmpty(ipAddress))
  333. return false;
  334. Regex validipregex = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
  335. return (ipAddress != "" && validipregex.IsMatch(ipAddress.Trim()));
  336. }
  337. }
  338. }