zoukankan      html  css  js  c++  java
  • 基于Task定时检测网络本地网络状况

    首先我们需要使用winInet.dll中的InternetGetConnectedState方法来检测本地是否连接网络,然后再通过ping的方式来获取网络状况。

    然后我们采用Task来开辟一个线程来定时检测网络状况,最后自定义一个委托,然后用事件来简单的通知网络状况。

    具体代码如下:

       public class NetWorkHelper
        {
           /// <summary>
           /// 委托
           /// </summary>
           /// <param name="flag"></param>
           /// <param name="msg"></param>
           public delegate void NetStatusDelegate(bool flag, string msg);
           public event NetStatusDelegate NetStatusEvent;
            public void StartCheck()
            {
                List<string> urlls = new List<string>() { "www.baidu.com", "www.sina.com", "www.cnblogs.com", "www.163.com", "www.csdn.com" };
                Task.Run(async () =>
                {
                    await Task.Run(() =>
                    {
                        while (true)
                        {
                            try
                            {
                                CheckServeStatus(urlls);
                            }
                            catch (Exception ex)
                            {
                                if (NetStatusEvent!=null)
                                {
                                    NetStatusEvent(false, "网络异常");
                                }
                            }
                            finally
                            {
                                System.Threading.Thread.Sleep(3000);
                            }
                        }
                    });
                });
            }
            // <summary>
            /// 检测网络连接状态
            /// </summary>
            /// <param name="urls"></param>
            public  void CheckServeStatus(List<string> urls)
            {
                int errCount = 0;//ping时连接失败个数
    
                if (!LocalConnectionStatus())
                {
                    if (NetStatusEvent != null)
                    {
                        NetStatusEvent(false, "网络异常--->无连接");
                    }
                }
                else if (!MyPing(urls, out errCount))
                {
                    if ((double)errCount / urls.Count >= 0.3)
                    {
                        if (NetStatusEvent != null)
                        {
                            NetStatusEvent(false, "网络异常--->连接多次无响应");
                        }
                       
                    }
                    else
                    {
                        if (NetStatusEvent != null)
                        {
                            NetStatusEvent(false, "网络异常--->网络不稳定");
                        }
                       
                    }
                }
                else
                {
                    if (NetStatusEvent != null)
                    {
                        NetStatusEvent(false, "网络正常");
                    }
                }
            }
            private const int INTERNET_CONNECTION_MODEM = 1;
            private const int INTERNET_CONNECTION_LAN = 2;
    
            [System.Runtime.InteropServices.DllImport("winInet.dll")]
            private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);
    
            /// <summary>
            /// 判断本地的连接状态
            /// </summary>
            /// <returns></returns>
            private static bool LocalConnectionStatus()
            {
                try
                {
                    System.Int32 dwFlag = new Int32();
                    if (!InternetGetConnectedState(ref dwFlag, 0))
                    {
                        Console.WriteLine("LocalConnectionStatus--未连网!");
                        return false;
                    }
                    else
                    {
                        if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
                        {
                            Console.WriteLine("LocalConnectionStatus--采用调制解调器上网。");
                            return true;
                        }
                        else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
                        {
                            Console.WriteLine("LocalConnectionStatus--采用网卡上网。");
                            return true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    
                  
                }
                return false;
            }
            /// <summary>
            /// Ping命令检测网络是否畅通
            /// </summary>
            /// <param name="urls">URL数据</param>
            /// <param name="errorCount">ping时连接失败个数</param>
            /// <returns></returns>
            public static bool MyPing(List<string> urls, out int errorCount)
            {
                try
                {
                    bool isconn = true;
                    Ping ping = new Ping();
                    errorCount = 0;
                    try
                    {
                        PingReply pr;
                        for (int i = 0; i < urls.Count; i++)
                        {
                            pr = ping.Send(urls[i]);
                            if (pr.Status != IPStatus.Success)
                            {
                                isconn = false;
                                errorCount++;
                            }
                        }
                    }
                    catch
                    {
                        isconn = false;
                        errorCount = urls.Count;
                    }
                    return isconn;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
            }
    
        }
    

      

  • 相关阅读:
    Mvcpager以下各节已定义,但尚未为布局页“~/Views/Shared/_Layout.cshtml”呈现:“Scripts”。
    骆驼男鞋怎么样,骆驼男鞋售后逆天,骆驼男鞋维修36天无结果。程序员屌丝的维权之路,直播。。。。。。
    IOS7状态栏StatusBar官方标准适配方法
    iphone原生cookie处理
    拼接语句单引号里面如何用单引号
    判断Linux 系统负荷是否过载
    sys用户无法远程登陆
    ORA-12838: cannot read/modify an object after modifying it in parallel
    ORA-19504: failed to create file "/u01/backup/db_0_20190603_1" ORA-27038: created file already exists
    oracle中job无法正常运行,如何排查
  • 原文地址:https://www.cnblogs.com/Koalin/p/11570216.html
Copyright © 2011-2022 走看看