gpt4 book ai didi

C# UDP广播和接收示例

转载 作者:可可西里 更新时间:2023-11-01 09:02:40 24 4
gpt4 key购买 nike

问题:我正在尝试在特定地址上绑定(bind)一个 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);
var task = 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);

task.Wait();

关于C# UDP广播和接收示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com