C#客户端连接服务器前先判断服务器连接是否正常
/// <summary>
/// 采用Socket方式,测试服务器连接
/// </summary>
/// <param name="host">服务器主机名或IP</param>
/// <param name="port">端口号</param>
/// <returns></returns>
public static bool TestConnection(string host, int port)
{
int millisecondsTimeout = 5;//等待时间
TcpClient client = new TcpClient();
try
{
var connect = client.BeginConnect(host, port, null, null);
connect.AsyncWaitHandle.WaitOne(millisecondsTimeout);
return client.Connected;
}
catch (Exception e)
{
//throw e;
return false;
}
finally
{
client.Close();
}
}
使用Ping命令检查IP地址或域名是否可以使用
/// <summary>
/// 用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令)
/// </summary>
/// <param name="strIpOrDName">IP地址或域名</param>
/// <returns></returns>
public static bool PingIpOrDomainName(string strIpOrDName)
{
try
{
Ping objPingSender = new Ping();
PingOptions objPinOptions = new PingOptions();
objPinOptions.DontFragment = true;
string data = "";
byte[] buffer = Encoding.UTF8.GetBytes(data);
int intTimeout = 120;
PingReply objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions);
string strInfo = objPinReply.Status.ToString();
if (strInfo == "Success")
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}