帮我写一个完整的:使用C#给产品发UDP广播,读取产品的回复
时间: 2024-12-10 11:42:07 浏览: 7
当然,我可以为您编写一个简单的C#程序,它使用UdpClient类来向指定的UDP IP地址和端口发送广播,并接收可能的响应。这里是一个基础示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class UdpBroadcastExample
{
private const string BroadcastAddress = "255.255.255.255"; // 广播地址
private const int BroadcastPort = 12345; // 指定端口
static void Main(string[] args)
{
// 创建 UDP 客户端
UdpClient client = new UdpClient(BroadcastPort);
try
{
// 发送广播消息
byte[] data = Encoding.ASCII.GetBytes("Hello, Product! This is a broadcast message.");
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse(BroadcastAddress), BroadcastPort);
client.SetSocketOption(SocketOptionLevel.Dgram, SocketOptionName.Broadcast, true);
client.Send(data, data.Length, groupEP);
Console.WriteLine("Broadcasted message to {0}:{1}", BroadcastAddress, BroadcastPort);
// 接收并打印回复
while (true)
{
IPEndPoint remoteEP = client.Receive(ref data);
Console.WriteLine("Received reply from {0}:\n{1}", remoteEP.Address.ToString(), Encoding.ASCII.GetString(data));
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
// 关闭连接
client.Close();
}
}
}
```
在这个例子中,我们创建了一个`UdpClient`,设置广播选项,然后发送一条广播消息。程序会进入无限循环等待接收来自其他设备的回应。
阅读全文