Implement a timer in C# to regularly determine whether the IP is pinged (connected) and whether the port number is reachable (available) via telnet

Scenes

When using HttpClient (setting the maximum timeout response time) in Winform to call the interface and do business processing, the interface gets stuck. Use async Task await to optimize asynchronous task programming:

When using HttpClient (setting the maximum timeout response time) in Winform to call the interface and do business processing, the interface gets stuck. Use async Task await to optimize asynchronous task programming_The Blog of Overbearing Rogue Temperament-CSDN Blog

On the basis of the above, change the timer to regularly call the http interface to regularly determine whether a certain IP is connected and whether the port is available.

Note:

Blog:
Domineering Rogue Temperament_C#, Architecture Road, SpringBoot-CSDN Blog

accomplish

1. When clicking the button on winform to start the timer

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

Bind event execution method

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

2. Implement it specifically in the checkApiIpAndPort method

        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. In addition to log output, there are two key methods, and they are implemented by asynchronous task programming.

Test whether the IP is connected to the IsIpReachable method implementation

        public async Task<bool> 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);
        }

The data to be sent can be specified at will.

Test whether the port can be implemented using the IsPortReachable method

        public async Task<bool> 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;
                }
            });
        }

Set the default port to 80 and the timeout to 2 seconds.

Note that the Timer here will have multiple namespaces, which can be specified directly as

using Timer = System.Windows.Forms.Timer;

4. Timer stops

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

Be careful to cancel event binding

5. Test effect

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/133271443