• C#中实现定时器Timer定时判断IP是否ping通(连通)和端口号是否telnet可达(可用)


    场景

    Winform中使用HttpClient(设置最大超时响应时间)调用接口并做业务处理时界面卡住,使用async Task await异步任务编程优化:

    Winform中使用HttpClient(设置最大超时响应时间)调用接口并做业务处理时界面卡住,使用async Task await异步任务编程优化_霸道流氓气质的博客-CSDN博客

    在上面的基础上,将定时器定时调用http接口改为定时判断某ip是否联通,端口是否可用。

    注:

    博客:
    霸道流氓气质_C#,架构之路,SpringBoot-CSDN博客

    实现

    1、winform上点击按钮启动定时器时

    1.                     _timer.Interval = scheduleInterval;                
    2.                     _timer.Tick += _timer_Tick;
    3.                     _timer.Start();

    绑定事件执行方法

    1.         private void _timer_Tick(object sender, EventArgs e)
    2.         {
    3.                 //其他业务操作
    4.                 checkApiIpAndPort();        
    5.         }

    2、在checkApiIpAndPort方法中具体实现

    1.         private async Task checkApiIpAndPort() {
    2.             textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":检测接口IP和端口联通状态进行中,解析接口ip为:" + Global.Instance.apiIpString + ",解析接口端口为:" + Global.Instance.apiPort);
    3.             textBox_log.AppendText("\r\n");
    4.             bool isIpViliable = await IsIpReachable(Global.Instance.apiIpString);   
    5.             bool isPortViliable = await IsPortReachable(Global.Instance.apiIpString, Global.Instance.apiPort);   
    6.      
    7.             textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":检测接口IP和端口联通状态执行结束,解析接口ip为:" + Global.Instance.apiIpString + ",ip连通性为:" + isIpViliable + ",解析接口端口为:" + Global.Instance.apiPort + ",端口连通性为:" + isPortViliable);
    8.             textBox_log.AppendText("\r\n");
    9.         }

    3、除了日志输出,就是两个关键的方法,并且是异步任务编程实现

    测试IP是否联通IsIpReachable方法实现

    1.         public async Task<bool> IsIpReachable(string strIP)
    2.         {
    3.             // Windows L2TP VPN和非Windows VPN使用ping VPN服务端的方式获取是否可以连通
    4.             Ping pingSender = new Ping();
    5.             PingOptions options = new PingOptions();
    6.             // Use the default Ttl value which is 128,
    7.             // but change the fragmentation behavior.
    8.             options.DontFragment = true;
    9.             // Create a buffer of 32 bytes of data to be transmitted.
    10.             string data = "badao";
    11.             byte[] buffer = Encoding.ASCII.GetBytes(data);
    12.             int timeout = 1500;
    13.             PingReply reply = pingSender.Send(strIP, timeout, buffer, options);
    14.             return (reply.Status == IPStatus.Success);
    15.         }

    发送的数据data随意指定即可。

    测试端口是否可用IsPortReachable方法具体实现

    1.         public async Task<bool> IsPortReachable(string host, int port = 80, int msTimeout = 2000)
    2.         {
    3.             return await Task.Run(() =>
    4.             {
    5.                 var clientDone = new ManualResetEvent(false);
    6.                 var reachable = false;
    7.                 var hostEntry = new DnsEndPoint(host, port);
    8.                 using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
    9.                 {
    10.                     var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry };
    11.                     socketEventArg.Completed += (s, e) =>
    12.                     {
    13.                         reachable = e.SocketError == SocketError.Success;
    14.                         clientDone.Set();
    15.                     };
    16.                     clientDone.Reset();
    17.                     socket.ConnectAsync(socketEventArg);
    18.                     clientDone.WaitOne(msTimeout);
    19.                     return reachable;
    20.                 }
    21.             });
    22.         }

    这么设置默认端口为80,超时时间为2秒

    注意这里的Timer会有多个namespace,直接指定为

    using Timer = System.Windows.Forms.Timer;

    4、定时器停止

    1.                 _timer.Tick -= _timer_Tick;
    2.                 _timer.Stop();

    注意要取消事件绑定

    5、测试效果

  • 相关阅读:
    LeetCode 周赛 340,质数 / 前缀和 / 极大化最小值 / 最短路 / 平衡二叉树
    查询当前日期,星期几,月份,第几周,是否是工作日
    2023国赛数学建模C题思路代码 - 蔬菜类商品的自动定价与补货决策
    springcloud springboot nacos版本对应
    白盒测试之测试用例设计方法
    Redis 5 种基本数据类型详解
    JS 添加数组元素( 4种方法 )
    泄漏libc基地址
    Java之反射获取和赋值字段
    面向对象-多态
  • 原文地址:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/133271443