C# UDP Broadcast and receive example(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 广播和接收示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# UDP 广播和接收示例
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01