c# 使用socket进行服务器健康检查

/// <summary>
        /// 采用Socket方式,测试服务器连接
        /// </summary>
        /// <param name="host">服务器主机名或IP</param>
        /// <param name="port">端口号</param>
        /// <param name="millisecondsTimeout">等待时间:毫秒</param>
        /// <returns></returns>
        public static bool TestConnection(string host, int port, int millisecondsTimeout=5)
        {
            TcpClient client = new TcpClient();
            try
            {
                var ar = client.BeginConnect(host, port, null, null);
                ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
                return client.Connected;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                client.Close();
            }
        }

 

使用场景:进行数据库访问前,可以检测数据库服务器是否正常连接;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章