简体   繁体   中英

c# receive udp broadcast packets with xml content (windows 7)

I want to receive udp packages in ac# program. the contents of several packages combined, are a XML Status Log. Which repeats after one status log is complete. See image below. I am using this UDP Broadcast example to get the packages, with port 53181 (see picture). But the program doesn't receive anything. Any ideas? How can I work with the received packages to get the XML data?

Wireshark屏幕

This is a general purpose receiver I made in class

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;
    }
}

The interface

public interface IBroadcastInterpreter
{
    void HandleBroadcast(byte[] input);
}

An example implementation could be:

class WriteToConsole : IBroadcastInterpreter
{
    public void HandleBroadcast(byte[] input)
    {
        string text = Encoding.ASCII.GetString(input);
        Console.WriteLine(text);
    }
}

This is a UDP broadcaster I made, to broadcast time.

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);
                        }
                    }
                });
    }

}

Create an instance of the WriteToConsole class, and pass it into the constructor of the broadcast receiver. Then any time a broadcast is received, it will use the implementation of the interface to do an action. In this case, as per your request - it will just write to the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM