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

 

使用場景:進行數據庫訪問前,可以檢測數據庫服務器是否正常連接;

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