string strCon = "Data Source=192.168.24.66;Initial Catalog=master;User ID=sa;password=123456;Connection Timeout=5";
#region 採用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) { 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(); } } #endregion
/// <summary> /// 數據庫鏈接操做,可替換爲你本身的程序 /// </summary> /// <param name="ConnectionString">鏈接字符串</param> /// <returns></returns> private static bool TestConnection(string ConnectionString) { bool result = true; try { SqlConnection m_myConnection = new SqlConnection(ConnectionString); m_myConnection.Open(); //數據庫操做...... m_myConnection.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); result = false; } return result; }我這裏用winForm來測試的。
private void btnSocket_Click(object sender, EventArgs e) { string strCon = "Data Source=192.168.24.566;Initial Catalog=qmaster;User ID=sa;password=123456"; string[] s=strCon.Split(';'); s = s[0].Split('='); //獲取IP string strIP =s[1]; //發送數據,判斷是否鏈接到指定ip if (TestConnection(strIP , 1433, 500)) { //鏈接成功 MessageBox.Show("Socket Link Succeed","鏈接服務器"); // 數據庫操做,我這裏用了鏈接測試。可根據你的系統自行修改 if (TestConnection(strCon)) MessageBox.Show("Sql Link Succeed","鏈接數據庫"); else MessageBox.Show("Sql Link Failed", "鏈接數據庫"); } else MessageBox.Show("Socket Link Failed","鏈接服務器"); }
版權聲明:本文爲博主原創文章,未經博主容許不得轉載。數據庫