C#UDP广播和接收示例 [英] C# UDP Broadcast and receive example

查看:126
本文介绍了C#UDP广播和接收示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我正在尝试在特定地址上绑定udp套接字.我将播出一条消息.相同的套接字将需要能够接收消息.

Problem: I am trying to bind a udp socket on a specific address. I will broadcast out a message. That same socket will need to be able to receive messages.

当前代码:

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/端口组合.

I am not receiving data on listen thread. I know that the code on the other side is functional, and sending a directed UDP message to the IP/Port combo.

推荐答案

可以简单地通过

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

这篇关于C#UDP广播和接收示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆