我想在c#程序中接收udp包。组合的几个包的内容是XML状态日志。在一个状态日志完成后重复。见下图。我使用this UDP Broadcast example来获取软件包,端口为53181(见图片)。 但该计划没有收到任何东西。有任何想法吗?如何使用收到的包来获取XML数据?
答案 0 :(得分:0)
这是我在课堂上制作的通用接收器
public class UdpBroadcastReceiver
{
private IBroadcastInterpreter _interpreter;
private volatile bool _shouldReceive = true;
/// <summary>
/// Will listen on all ports for udp broadcasts - Will handle input with interpreter
/// </summary>
/// <param name="interpreter"></param>
public UdpBroadcastReceiver(IBroadcastInterpreter interpreter)
{
_interpreter = interpreter;
}
/// <summary>
/// Will listen for a broadcast indefinetly. Will lock up your program.
/// Use Task.Run to start listening. Then you can use StopListening to break the loop.
/// </summary>
public void ListenForBroadcast(int port)
{
using (UdpClient client = new UdpClient(port))
{
IPEndPoint senderEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (_shouldReceive)
{
byte[] receiveBuffer = client.Receive(ref senderEndPoint); // execution will stop and wait for data.
_interpreter?.HandleBroadcast(receiveBuffer);
}
}
}
/// <summary>
/// Breaks the while loop in ListenForBroadcast
/// </summary>
public void StopListening()
{
_shouldReceive = false;
}
}
界面
public interface IBroadcastInterpreter
{
void HandleBroadcast(byte[] input);
}
示例实现可以是:
class WriteToConsole : IBroadcastInterpreter
{
public void HandleBroadcast(byte[] input)
{
string text = Encoding.ASCII.GetString(input);
Console.WriteLine(text);
}
}
这是我制作的UDP广播公司,用于广播时间。
class UdpBroadcaster
{
private int _port;
private bool shouldRun = true;
public UdpBroadcaster(int port)
{
_port = port;
}
public void Stop()
{
shouldRun = false;
}
public void Start()
{
Trace.TraceInformation("Entered start method");
Task.Run(() =>
{
Trace.TraceInformation("Started task");
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Broadcast, _port);
using (UdpClient client = new UdpClient())
{
Trace.TraceInformation("Entered using statement");
client.EnableBroadcast = true;
while(shouldRun)
{
Trace.TraceInformation("Started while loop");
byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToString(new CultureInfo("da-dk")));
client.Send(data, data.Length, serverEndPoint);
Trace.TraceInformation("waiting 5 seconds");
Thread.Sleep(5 * 1000);
}
}
});
}
}
创建WriteToConsole类的实例,并将其传递给广播接收器的构造函数。然后,只要接收到广播,它就会使用接口的实现来执行操作。在这种情况下,根据您的要求 - 它只会写入控制台。