private void udpGetMACIPAndSendCheck() { UdpClient udpServer = new UdpClient(50001); udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpServer.Client.ReceiveTimeout = 1000; while (true) { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = { }; if (running == false) { break; } // 这里使用超时退出一次,主要是为了解决按下Stop的时候需要退出,需要杀死线程导致的。 try { receiveBytes = udpServer.Receive(ref RemoteIpEndPoint); } catch { continue; } Console.WriteLine("udp received."); string mac = Encoding.ASCII.GetString(receiveBytes); string ip = RemoteIpEndPoint.Address.ToString(); MACIP macip = new MACIP(mac, ip); // 检查IP是否已经存在ArrayList中,删除,并重新添加,就没有必要添加到其中 lock (threadLock) { int count = 0; for (; count < macIpAL.Count; count++) { if (((MACIP)macIpAL[count]).IP == ip) { break; } } if (macIpAL.Count > 0 && count < macIpAL.Count) { ((MACIP)(macIpAL[count])).LeftTime = MACIP.LEFT_TIME; } else { macIpAL.Add(macip); } } // 让线程去更新UI界面 refreshListViewFlag = true; Console.WriteLine("lv refresh. macIpAL count: {0}", macIpAL.Count); } }
/// <summary> /// 1. 获取IP; /// 2. 获取IP对应的MACIP对象,如果不在范围,直接返回,线程结束; /// 3. 获取客户端的数据,并更新MACIP对应的心跳时间; /// 4. 连接异常或者断开之后关闭socket; /// 5. 删除Arraylist中的对象。 /// </summary> public void RunThread() { string ip = ((IPEndPoint)(clientSocket.RemoteEndPoint)).Address.ToString(); Console.WriteLine("RecvThread ip : {0}", ip); int index = 0; for (; index < macIpAL.Count; index++) { if (((MACIP)macIpAL[index]).IP == ip) { macip = ((MACIP)macIpAL[index]); macip.ClientSocket = this.clientSocket; Console.WriteLine("RecvThread ClientSocket value {0}", this.clientSocket == null); Console.WriteLine("RecvThread add ClientSocket {0}", macip.ClientSocket); break; } } if (index >= macIpAL.Count) { // clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); return; } while (LocalDetect.localDetect.running) { try { //通过clientSocket接收数据 int receiveNumber = clientSocket.Receive(result); if (receiveNumber == 0) { break; } macip.LeftTime = 4; Console.WriteLine("接收客户端{0}消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)); } catch { break; } } try { Console.WriteLine("recvThread close socket."); macip.ClientSocket.Shutdown(SocketShutdown.Both); macip.ClientSocket.Close(); } catch { } // 确认存在之后再去删除 if (macIpAL.Contains(macip)) { macIpAL.Remove(macip); } LocalDetect.localDetect.refreshListViewFlag = true; }