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

场景

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

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

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

注:

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

实现

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

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

绑定事件执行方法

        private void _timer_Tick(object sender, EventArgs e)
        {
                //其他业务操作
                checkApiIpAndPort();        
        }

2、在checkApiIpAndPort方法中具体实现

        private async Task checkApiIpAndPort() {
            textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":检测接口IP和端口联通状态进行中,解析接口ip为:" + Global.Instance.apiIpString + ",解析接口端口为:" + Global.Instance.apiPort);
            textBox_log.AppendText("\r\n");

            bool isIpViliable = await IsIpReachable(Global.Instance.apiIpString);   
            bool isPortViliable = await IsPortReachable(Global.Instance.apiIpString, Global.Instance.apiPort);   
     
            textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":检测接口IP和端口联通状态执行结束,解析接口ip为:" + Global.Instance.apiIpString + ",ip连通性为:" + isIpViliable + ",解析接口端口为:" + Global.Instance.apiPort + ",端口连通性为:" + isPortViliable);
            textBox_log.AppendText("\r\n");
        }

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

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

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

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

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

        public async Task IsPortReachable(string host, int port = 80, int msTimeout = 2000)
        {
            return await Task.Run(() =>
            {
                var clientDone = new ManualResetEvent(false);
                var reachable = false;
                var hostEntry = new DnsEndPoint(host, port);
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry };
                    socketEventArg.Completed += (s, e) =>
                    {
                        reachable = e.SocketError == SocketError.Success;
                        clientDone.Set();
                    };
                    clientDone.Reset();
                    socket.ConnectAsync(socketEventArg);
                    clientDone.WaitOne(msTimeout);
                    return reachable;
                }
            });
        }

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

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

using Timer = System.Windows.Forms.Timer;

4、定时器停止

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

注意要取消事件绑定

5、测试效果

C#中实现定时器Timer定时判断IP是否ping通(连通)和端口号是否telnet可达(可用)_第1张图片

你可能感兴趣的:(C#,c#,tcp/ip,开发语言)