/// <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(); } }
使用場景:進行數據庫訪問前,可以檢測數據庫服務器是否正常連接;