C# UDP 广播和接收示例

C# UDP Broadcast and receive example(C# UDP 广播和接收示例)
本文介绍了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;
                }
            }
});
}   

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

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 广播和接收示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)