C#UDP广播和接收示例

前端之家收集整理的这篇文章主要介绍了C#UDP广播和接收示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题:
我试图在特定地址绑定一个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消息.

解决方法

它可以简单地完成
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);
原文链接:https://www.f2er.com/c/110304.html

猜你在找的C&C++相关文章