使用UDPClient获取多播消息

时间:2017-05-30 19:33:08

标签: c#

我已将产品直接插入计算机的以太网端口,将组播数据包发送到224.224.10.10和UDP端口24588.我已经在下面的代码中设置了我的UDP客户端,我觉得就像我设置正确,但我仍然没有收到任何数据包。我总是抓到一个例外,说我等待回复。有什么想法或明显的错误吗?

在发布此问题之前,我查看了很多问题,但我无法获得解决方案,而且我无法找到与我拥有相同类型设置的任何人。

public class ReceiverClass
{
    private UdpClient m_UDPClient = null;
    private Thread m_UDPReceiverThread = null;
    private bool m_ContinueReceiving = false;
    private readonly object m_sync = new object();
    private const int UDP_PORT = 24588;

    public ReceiverClass()
    {
        m_ContinueReceiving = true;
        m_UDPClient = new UdpClient(UDP_PORT);
        m_UDPClient.Client.ReceiveTimeout = 20000;

        m_UDPReceiverThread = new Thread(ReceiveData) { IsBackground = true };
        m_UDPReceiverThread.Start();
    }

    private void ReceiveData()
    {
        bool Continue;
        byte[] ReceiveBuffer;
        IPEndPoint defaultIP = new IPEndPoint(IPAddress.Any, 0);

        m_UDPClient.JoinMulticastGroup(IPAddress.Parse("224.224.10.10")); 
        m_UDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

        lock (m_sync)
        {
            Continue = m_ContinueReceiving;
        }

        while (Continue)
        {
            try
            {
                ReceiveBuffer = m_UDPClient.Receive(ref defaultIP);

                if (null != ReceiveBuffer)
                {
                    // Do stuff with received...
                }
            }
            catch (Exception e)
            {
                // ooo eee kill stream
                Dispose(false);
                return;
            }
            finally
            {
                lock (m_sync)
                {
                    Continue = m_ContinueReceiving;
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我看不出你的代码有什么问题,所以我没有给你一个合适的答案。但是,这是我用来获取UDP广播消息的一段代码。希望它能为你工作,或者给你一些新的想法:

class UdpHandler {

    public UdpHandler(int portNo) {
        Thread t = new Thread(ListenThread);
        t.IsBackground = true;
        t.Start(portNo);
    }

    public void ListenThread(object portNo) {
        UdpClient client = new UdpClient { ExclusiveAddressUse = false };
        IPEndPoint localEp = new IPEndPoint(IPAddress.Any, (int)port);
        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        client.ExclusiveAddressUse = false;
        client.Client.Bind(localEp);

        while (true) {
            byte[] data = client.Receive(ref localEp);
            DataReceived(data);
        }
    }

    private void DataReceived(byte[] rawData) {
        // Handle the received data
    }
}

答案 1 :(得分:0)

我最终做的是进入Sockets类并查看原始数据包并选择我需要的内容。我将套接字绑定到我的lan接口,并嗅出东西。我不得不以管理员身份运行它以使其工作,但那很好。我走这条路是因为我可以看到wireshark中的数据包,但是它们并没有到达我的udpclient。这最终是获得我想要的最快方式。

{{1}}