使用UdpClient和JoinMulticastGroup在C#中发现Belkin Wemo交换机

使用UdpClient和JoinMulticastGroup在C#中发现Belkin Wemo交换机,c#,udp,multicast,upnp,ssdp,C#,Udp,Multicast,Upnp,Ssdp,我正在尝试使用C#发现Belkin Wemo开关。我通过网络发送SSDP以从交换机获取响应 下面的代码段创建一个套接字,发送SSDP并等待2秒钟以接收应答。如果没有读取任何内容,则会重新开始 bool repeat = true; while (repeat) { UdpClient udpClient = null; try { // Creates the socket. udpClient = new UdpClient(10140)

我正在尝试使用C#发现Belkin Wemo开关。我通过网络发送SSDP以从交换机获取响应

下面的代码段创建一个套接字,发送SSDP并等待2秒钟以接收应答。如果没有读取任何内容,则会重新开始

bool repeat = true;
while (repeat)
{
    UdpClient udpClient = null;
    try
    {
        // Creates the socket.
        udpClient = new UdpClient(10140);
        udpClient.Client.ReceiveTimeout = 2000;
        IPAddress broadcastIpAddress = IPAddress.Parse("239.255.255.250");
        IPEndPoint broadcastIpEndPoint = new IPEndPoint(broadcastIpAddress, 1900);
        udpClient.JoinMulticastGroup(broadcastIpAddress);

        // Sends SSDP.
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append("M-SEARCH * HTTP/1.1\r\n");
        stringBuilder.Append("ST: urn:Belkin:service:basicevent:1\r\n");
        stringBuilder.Append("MX: 1\r\n");
        stringBuilder.Append("MAN: \"ssdp:discover\"\r\n");
        stringBuilder.Append("HOST: 239.255.255.250:1900\r\n");
        stringBuilder.Append("\r\n");
        byte[] bytesToSend = Encoding.UTF8.GetBytes(stringBuilder.ToString());
        udpClient.Send(bytesToSend, bytesToSend.Length, broadcastIpEndPoint);

        // Receives response.
        IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        byte[] receivedBytes = udpClient.Receive(ref remoteIpEndPoint);
        string receivedString = Encoding.UTF8.GetString(receivedBytes);
        Console.WriteLine(receivedString);

        repeat = false;
    }
    catch (SocketException) { }
    finally 
    {
        udpClient.Close();
    }
}
大多数情况下,开关会返回响应。然而,有时它无限期地循环,而没有得到任何反馈


我正在使用Wireshark。在第二种情况下,没有发送SSDP。我对此没有解释。我的系统是Windows 7,也许它有助于…

catch(SocketException){}
这里的一些实际错误处理可能会提供新的想法,因为我现在遇到了类似的问题。除了像在所有指南中一样直接使用
Socket
之外,您是否找到了解决方案?
catch(SocketException){}
这里的一些实际错误处理可能会提供新的思路,因为我现在遇到了类似的问题。除了像在所有指南中一样直接使用
Socket
,您还找到了解决方案吗?