Implemente un temporizador en C# para determinar periódicamente si se hace ping a la IP (está conectada) y si el número de puerto es accesible (disponible) a través de telnet.

Escenas

Cuando se usa HttpClient (estableciendo el tiempo máximo de respuesta de tiempo de espera) en Winform para llamar a la interfaz y realizar procesamiento comercial, la interfaz se atasca. Utilice async Task await para optimizar la programación de tareas asincrónicas:

Cuando se utiliza HttpClient (estableciendo el tiempo máximo de respuesta de tiempo de espera) en Winform para llamar a la interfaz y realizar procesamiento comercial, la interfaz se atasca. Utilice la tarea asíncrona en espera para optimizar la programación de tareas asincrónicas_The Blog of Overbearing Rogue Temperament-CSDN Blog

Sobre la base de lo anterior, cambie el temporizador para llamar periódicamente a la interfaz http para determinar periódicamente si una determinada IP está conectada y si el puerto está disponible.

Nota:

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

lograr

1. Al hacer clic en el botón en winform para iniciar el temporizador

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

Vincular método de ejecución de eventos

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

2. Implementarlo específicamente en el método 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. Además de la salida del registro, existen dos métodos clave y se implementan mediante programación de tareas asincrónicas.

Pruebe si la IP está conectada a la implementación del método IsIpReachable

        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);
        }

Los datos a enviar se pueden especificar a voluntad.

Pruebe si el puerto se puede implementar utilizando el método IsPortReachable

        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;
                }
            });
        }

Establezca el puerto predeterminado en 80 y el tiempo de espera en 2 segundos.

Tenga en cuenta que el temporizador aquí tendrá múltiples espacios de nombres, que se pueden especificar directamente como

using Timer = System.Windows.Forms.Timer;

4. El cronómetro se detiene

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

Tenga cuidado al cancelar el enlace del evento

5. Efecto de prueba

Supongo que te gusta

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/133271443
Recomendado
Clasificación