2016-11-15 238 views
3

問題: 我想綁定特定地址上的udp套接字。我會播出一條消息。相同的套接字將需要能夠接收消息。C#UDP廣播和接收示例

當前代碼:

static void Main() 
{ 
    UdpClient Configuration = new UdpClient(new IPEndPoint(IPAddress.Parse(data.IPAddress), configuration.Port)); //set up the bind to the local IP address of my choosing 
    ConfigurationServer.EnableBroadcast = true; 
    Configuration.Connect(new IPEndpoint(IPAddress.Parse(data.BroadcastIP), configuration.Port); 
    Listen(); 

} 

private void Listen() 
{ 
    Task.Run(async() => 
      { 
       while (true) 
       { 
        var remoteIp = new IPEndPoint(IPAddress.Any, configuration.Port); 
        var data = await ConfigurationServer.ReceiveAsync(); 

        // i would send based on what data i received here 
        int j = 32; 
       } 
      } 
}); 
} 

我沒有收到監聽線程數據。我知道另一端的代碼是可用的,併發送一個定向的UDP消息給IP/Port組合。

+1

我投票關閉這一問題作爲題外話,因爲這個問題是最適合的代碼審查SE可以簡單地做! –

+5

此問題的特徵代碼不能按預期工作(ala:缺少預期功能)。因此,對於CR來說,這是** off-topic **。 – Sumurai8

回答

4

int PORT = 9876; 
UdpClient udpClient = new UdpClient(); 
udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, PORT)); 

var from = new IPEndPoint(0, 0); 
Task.Run(() => 
{ 
    while (true) 
    { 
     var recvBuffer = udpClient.Receive(ref from); 
     Console.WriteLine(Encoding.UTF8.GetString(recvBuffer)); 
    } 
}); 

var data = Encoding.UTF8.GetBytes("ABCD"); 
udpClient.Send(data, data.Length, "255.255.255.255", PORT); 
+1

就這麼簡單。謝謝您的幫助。 – Jason