我正在实现一个udp发现协议,其中我向本地网络广播消息,并从定制硬件(或硬件的模拟器)或多个响应接收消息,具体取决于网络上存在多少实例 .

我的广播工作正常,但接收部分有一些问题:我看到我发送的广播,但从未看到硬件响应 . 我知道硬件正在发送广播,因为当我监视该端口上的流量时,我看到它们进入了wireshark .

我究竟做错了什么?

IPEndPoint receiveIpEndPoint = new IPEndPoint(IPAddress.Any, 777);

private List<string> FindIPs() {
        string message = "{\"TCS\":{\"IP\":\"" + GetLocalIPAddress().ToString() + "\", \"Port\":777}}"; 
        byte[] tempBytes = ASCIIEncoding.ASCII.GetBytes(message);
        IPEndPoint broadcastIpEndPoint = new IPEndPoint(IPAddress.Broadcast, 777); 

        // list of UdpClients to send 
        List<UdpClient> sendClients = new List<UdpClient>();
        foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) {
            if ((!networkInterface.Supports(NetworkInterfaceComponent.IPv4)) ||
                (networkInterface.OperationalStatus != OperationalStatus.Up)) {
                continue;
            }

            IPInterfaceProperties adapterProperties = networkInterface.GetIPProperties();
            UnicastIPAddressInformationCollection unicastIPAddresses = adapterProperties.UnicastAddresses;
            IPAddress ipAddress = null;

            foreach (UnicastIPAddressInformation unicastIPAddress in unicastIPAddresses) {
                if (unicastIPAddress.Address.AddressFamily != AddressFamily.InterNetwork) {
                    continue;
                }
                ipAddress = unicastIPAddress.Address;
                break;
            }

            if (ipAddress == null) {
                continue;
            }

            UdpClient sendClient = new UdpClient(new IPEndPoint(ipAddress, 0));
            sendClients.Add(sendClient);
        }

        var udpreceive = new UdpClient(receiveIpEndPoint);
        udpreceive.BeginReceive(new AsyncCallback(ProcessUDPResponse), udpreceive);

        Log(message, LogManager.GetLogger("Sent UDP broadcast"));
        foreach (var udp in sendClients) {
            udp.EnableBroadcast = true;
            udp.Send(tempBytes, tempBytes.Length, broadcastIpEndPoint);
        }

        while(addresses.Count < 1) {

        }
        return addresses;
    }

    private void ProcessUDPResponse(IAsyncResult result) {
        UdpClient udp = result.AsyncState as UdpClient;
        string returnData = Encoding.ASCII.GetString(udp.EndReceive(result, ref receiveIpEndPoint));
        Console.WriteLine("**************           " + returnData.ToString());
        if (returnData.Contains("MAC")) {
            addresses.Add(receiveIpEndPoint.Address.ToString());
        }
        udp.BeginReceive(new AsyncCallback(ProcessUDPResponse), udp);
    }