代码之家  ›  专栏  ›  技术社区  ›  Hafiz H

无法调试UDP客户端接收

  •  0
  • Hafiz H  · 技术社区  · 9 年前

    我想使用以下端口从下面的IP地址接收数据包。问题出现在 “client.Receive(ref localEp);” 此行代码无法运行,也无法调试。

    UdpClient client = new UdpClient();
    
    IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 17000);
    client.Client.Bind(localEp);
    
    IPAddress multicastaddress = IPAddress.Parse("224.0.0.10");
    client.JoinMulticastGroup(multicastaddress);
    
    while (true)
    {
         Byte[] data = client.Receive(ref localEp);
         string strData = Encoding.UTF8.GetString(data);
         Console.WriteLine(strData);
    }
    

    我还得到了这个异常ScopeId='localEp.Address。ScopeId引发了“System.Net.Sockets”类型的异常。IPEndPoint localEp中的“SocketException”。请帮助更正我的代码

    解决方案是,在我的机器上安装了HYPER-V虚拟机设置,这限制了此udp数据的接收。我刚刚禁用它并开始接收数据。老实说,我不知道它的行为。

    1 回复  |  直到 9 年前
        1
  •  1
  •   Zag Gol    9 年前

    首先尝试使用msdn方式从localhost的任何源接收数据,然后从其他主机名接收数据:

    https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient(v=vs.110).aspx

    // This constructor arbitrarily assigns the local port number.
        UdpClient udpClient = new UdpClient(17000);
    
        udpClient.Connect("127.0.0.1", 17000);
    
        // Sends a message to the host to which you have connected.
        Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
    
        udpClient.Send(sendBytes, sendBytes.Length);
    
        //// Sends a message to a different host using optional hostname and port parameters.
        //UdpClient udpClientB = new UdpClient();
        //udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 17000);
    
        //IPEndPoint object will allow us to read datagrams sent from any source.
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    
        // Blocks until a message returns on this socket from a remote host.
        Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
        string returnData = Encoding.ASCII.GetString(receiveBytes);