如何判断网络连接的方法集锦
在网络应用程序中经常会判断网络是否正常或者是否能够正常联机到远程服务器,就上述问题,目前提供了如下集中方法,供大家参考.
一.使用.Net 2.0提供的Ping命令
二.使用本地tcp集合,此集合由操作系统层面提供,也是.Net2.0支持的
一.使用.Net 2.0提供的Ping命令
1 AutoResetEvent waiter = new AutoResetEvent(false);
2 Ping myPing = new Ping();
3 myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);
4 string data = "OK"; //Ping 发送的数据
5 byte[] buffer = Encoding.ASCII.GetBytes(data);
6 int timeout = 10000;
7 PingOptions options = new PingOptions(64, true);
8 myPing.SendAsync(_AppState.ServerName, timeout, buffer, options, waiter);
2 Ping myPing = new Ping();
3 myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);
4 string data = "OK"; //Ping 发送的数据
5 byte[] buffer = Encoding.ASCII.GetBytes(data);
6 int timeout = 10000;
7 PingOptions options = new PingOptions(64, true);
8 myPing.SendAsync(_AppState.ServerName, timeout, buffer, options, waiter);
二.使用本地tcp集合,此集合由操作系统层面提供,也是.Net2.0支持的
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
foreach (TcpConnectionInformation info in connections) {
if (info.RemoteEndPoint.Equals(targetEndPoint)) {
_AppState.OnlineStatus = Constant.ONLINE_STATUS_ONLINE;
isOnline = true;
break;
}
}
其中在集合中遍历是否存在对应的远程主机名称和端口号,使用这个方法的前提时必须能在第一次运行的时候连接到远程服务器.否则在集合中是查找不到的.
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
foreach (TcpConnectionInformation info in connections) {
if (info.RemoteEndPoint.Equals(targetEndPoint)) {
_AppState.OnlineStatus = Constant.ONLINE_STATUS_ONLINE;
isOnline = true;
break;
}
}