首页 文章

使用udpClient连续接收消息

提问于
浏览
20

我正在寻找通过 C# 中的 UdpClient 类接收和处理消息的最佳解决方案 . 有没有人有这方面的解决方案?

3 回答

  • 16

    试试这段代码:

    //Client uses as receive udp client
    UdpClient Client = new UdpClient(Port);
    
    try
    {
         Client.BeginReceive(new AsyncCallback(recv), null);
    }
    catch(Exception e)
    {
         MessageBox.Show(e.ToString());
    }
    
    //CallBack
    private void recv(IAsyncResult res)
    {
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8000);
        byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);
    
        //Process codes
    
        MessageBox.Show(Encoding.UTF8.GetString(received));
        Client.BeginReceive(new AsyncCallback(recv), null);
    }
    
  • 39

    对于使用TAP而不是Begin / End方法的较新方法,您可以在.Net 4.5中使用以下方法

    非常简单!

    异步方法

    private static void UDPListener()
        {
            Task.Run(async () =>
            {
                using (var udpClient = new UdpClient(11000))
                {
                    string loggingEvent = "";
                    while (true)
                    {
                        //IPEndPoint object will allow us to read datagrams sent from any source.
                        var receivedResults = await udpClient.ReceiveAsync();
                        loggingEvent += Encoding.ASCII.GetString(receivedResults.Buffer);
                    }
                }
            });
        }
    

    同步方法

    与上面的 asynchronous 方法一样,这也可以在 synchronous 方法中以非常类似的方式实现:

    private static void UDPListener()
        {
            Task.Run(() =>
            {
                using (var udpClient = new UdpClient(11000))
                {
                    string loggingEvent = "";
                    while (true)
                    {
                        //IPEndPoint object will allow us to read datagrams sent from any source.
                        var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        var receivedResults = udpClient.Receive(ref remoteEndPoint);
                        loggingEvent += Encoding.ASCII.GetString(receivedResults);
                    }
                }
            });
        }
    
  • 0

    我可以推荐两个关于这个解决方案的链接,对我有帮助 .

    PC Related

    Stack Overflow

    第一个是非常简单的解决方案,但要小心修改,因为只有当一些UDP数据包作为第一个发送到“远程”设备时,连续接收才会起作用 . 对于连续监听,添加代码行“udp.BeginReceive(new AsyncCallback(UDP_IncomingData),udp_ep);”在每次读取数据后,启用新的UDP数据包接收 .

    第二个是使用多播IP地址的好方法(239.255.255.255 - 240.0.0.0)

相关问题