2016-09-15 137 views
0

我想使用以下端口從下面的IP地址接收數據包。問題出在「client.Receive(ref localEp);」之後這行代碼不運行,也無法調試。無法調試UDPclient客戶端接收

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' 在IPEndPoint localEp投擲型 'System.Net.Sockets.SocketException' 的一個例外。請幫助糾正我的代碼

UPDATE解決方法是,在我的機器上安裝了HYPER-V虛擬機安裝程序,該安裝程序限制了此udp數據的接收。我只是禁用它,並開始接收數據。說實話,我不知道它的行爲。

+0

也許問題是端口17000嘗試其他端口。 –

+0

我檢查了一些其他值和默認值0,同樣的問題! :( –

回答

1

首先嚐試MSDN方式從本地主機從任何來源獲得數據,然後從其他主機名:

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); 
+0

工作正常與本地主機。我猜問題是與服務器,這是不發送任何數據。順便說一句,感謝您的答案 –

+0

它與從本地主機服務器接收數據? –

+0

是的,工作,即使當Hyper -V已啓用 –