【问题标题】:UDPClient loosing connection after receiving multiple messagesUDPClient收到多条消息后失去连接
【发布时间】:2024-01-08 18:39:01
【问题描述】:

我正在尝试获取一些通过 UDP 多播服务器流式传输的数据。我编写了一个 C# WPF 应用程序,我可以在其中输入服务器的端口和 IP 地址。与服务器的连接已成功建立,我可以接收多个数据包(50-500 个数据包,每次尝试不同)

我每 33 毫秒通过调度程序调用一次接收函数。较长的调度程序事件之间的时间,并不能解决问题。

几秒钟后,UDPClient 断开连接,无法接收数据,也无法再建立连接。

这里是按钮建立连接并启动调度器的功能:

public int connectToArtWelder()
        {
            if (!checkIPAddress())
            {
                MessageBox.Show("Please enter a valid IP-Address.", "Wrong IP-Address", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                string iPString = tB_weldConIP.Text;
                int port = Convert.ToInt32(tB_weldConPort.Text);
                IPAddress iPAddress = IPAddress.Parse(iPString);
                udpClient.Connect(iPAddress, port);

                try
                {
                    dispatcherTimer2.Tick += new EventHandler(Receive);
                    dispatcherTimer2.Interval = new TimeSpan(0, 0, 0, 0, 33);
                    dispatcherTimer2.Start();
                }
                catch
                {

                }
            }
            return 0;
        }

这里是接收函数:

    private void Receive(object sender, EventArgs e)
    {
        try
        {
            int condition = udpClient.Available;
            if (condition > 0)
            { 
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            var asyncResult = udpClient.BeginReceive(null, null);
            asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(10));
                if (asyncResult.IsCompleted)
                {
                    byte[] receiveBytes = udpClient.EndReceive(asyncResult, ref RemoteIpEndPoint);
                    double[] d = new double[receiveBytes.Length / 8];
                    // Do something with data
                }
            }
            else
            {
                // The operation wasn't completed before the timeout and we're off the hook
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

如果有人遇到任何相同的问题或解决我的问题,请告诉我。

【问题讨论】:

  • “UDPClient 失去连接” UDP 是无连接的。那么,这到底是什么意思呢?你有任何异常,还是只是不再收到任何东西?
  • catch { } = 坏主意。
  • 您对 APM(异步编程模型)的使用也不太正确。如果接收操作超过您的超时时间,您似乎会丢弃结果。
  • EndReceive 需要在 BeginReceive 之前。结束获取当前消息并开始注册接收事件,以便您可以获得更多数据。查看 msdn 示例:docs.microsoft.com/en-us/dotnet/framework/network-programming/…
  • “EndReceive 需要在 BeginReceive 之前”但是我应该如何对 asyncResult 做出反应?

标签: c# wpf udp udpclient


【解决方案1】:

解决方案: 我刚刚删除了

udpClient.Connect(ipAddress, port);

命令,现在它运行超级流畅。

【讨论】: