udpclient.receive() 突然停止接收

udpclient.receive() suddenly stops receiving


我正在使用 UdpClient 从单个主机接收数据(实际上它是一个微控制器,每 4 毫秒发送 32 个字节的数据。
我写的程序很简单。
我正在像这样初始化 UdpClient(在 Program.cs 中):

public static UdpClient client = new UdpClient(1414);

之后我在 Form_Load 事件中这样做:

static UdpClient client = Program.client; 
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

然后像这样调用 client.Recieve()

                Task.Run(() =>
                {
                    while (true)
                    {                       
                        try
                        {
                            data = client.Receive(ref RemoteIpEndPoint);                            
                        }
                        catch (Exception ex)
                        {
                            String err_type = ex.GetType().Name;
                            if (err_type == "SocketException")
                            {                                    
                                MessageBox.Show("Cannot Find The Device.", "Device Error.");
                            }
                        }                                                        
                    }
                });

程序 运行 在我自己的系统上运行良好(使用 Windows 10)。然而,当我 运行 这个程序在 windows 7 时,在随机时间,但有 100% 的机会 client.Recieve() 停止工作并且程序不再接收任何数据。没有异常被抛出。为了找到问题的根源,我安装了 Wireshark 来测试是否有任何传入 data.The 答案是没有(LAN 端口灯也停止闪烁)。让我感到困惑的是,这不会发生在 windows 10.

事实是,您错过了除 SocketException 之外的所有异常。 要找出发生了什么,请重写您的 catch 块:

Task.Run(() =>
                {
                    while (true)
                    {                       
                        try
                        {
                            data = client.Receive(ref RemoteIpEndPoint);                            
                        }
                        catch (SocketException ex)
                        {

                                MessageBox.Show("Cannot Find The Device.", "Device Error.");

                        }  
                        catch (Exception e)
                        {
                                MessageBox.Show(e.GetType().Name, e.Message);
                        }

                    }
                });

原来我的代码完全没问题。
这是我们这边的硬件问题。