UDPClient收到多条消息后失去连接

问题描述 投票:0回答:1

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

我每33ms通过一个调度程序调用一次接收函数。调度程序事件之间的时间过长,无法解决问题。

几秒钟后,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());
        }
    }

请让我知道是否有人遇到同样的问题或解决我的问题的方法。

Ty

c# wpf udp udpclient
1个回答
0
投票

它看起来像是因为您在一次监听后停止监听UDP客户端。

            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            while(udpClient.Available > 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
                }

如果将其更改为while循环,它将查找数据,直到UDP连接不再可用。

© www.soinside.com 2019 - 2024. All rights reserved.