#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;
}
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","连接服务器");
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有