【问题标题】:C# UDP Broadcast and receive exampleC# UDP 广播和接收示例
【发布时间】:2016-11-15 18:15:24
【问题描述】:

问题: 我正在尝试在特定地址上绑定 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;
                }
            }
});
}   

我没有在监听线程上接收数据。我知道另一端的代码可以正常工作,并向 IP/端口组合发送定向 UDP 消息。

【问题讨论】:

  • 此问题的代码无法按预期工作(ala:缺少预期的功能)。因此,对于 CR,它是题外话

标签: c# udp


【解决方案1】:

它可以简单地完成

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

【讨论】:

  • 什么是 255.255.255.255?
  • @Kiquenet 它是网络上的广播地址。发送到广播地址的消息将被发送到网络上的所有设备。 en.wikipedia.org/wiki/Broadcast_address
  • 这个程序不等待响应就立即退出
  • @bturner1273 这是因为它是一个代码sn-p 不是一个完整的程序。如果您正在编写控制台应用程序,请在 Main 函数的末尾添加一个阻塞代码,例如 Console.ReadLine
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 2012-09-17
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2011-12-07
相关资源
最近更新 更多