企业营销型网站建设的可行性分析,网络营销方式有哪些分类,公司网站制作,爱网聊的男人是什么心理咨询区 Mohit Deshpande我的项目有一个需求#xff0c;需要检查网络的连通性#xff0c;请问是否有高效的方式去实现#xff1f;回答区 Leo虽然并不能完全可靠的实现网络连通性检查#xff0c;因为你不能保证目标机永远在线#xff0c;相比来说更高效的方式是用 Ping协议 … 咨询区 Mohit Deshpande我的项目有一个需求需要检查网络的连通性请问是否有高效的方式去实现回答区 Leo虽然并不能完全可靠的实现网络连通性检查因为你不能保证目标机永远在线相比来说更高效的方式是用 Ping协议 而不是 Http协议比如说你可以不断的 ping google.com参考如下代码public static bool Isconnected false;public static bool CheckForInternetConnection()
{try{Ping myPing new Ping();String host google.com;byte[] buffer new byte[32];int timeout 1000;PingOptions pingOptions new PingOptions();PingReply reply myPing.Send(host, timeout, buffer, pingOptions);if (reply.Status IPStatus.Success){return true;}else if (reply.Status IPStatus.TimedOut){return Isconnected;}else{return false;}}catch (Exception){return false;}
}public static void CheckConnection()
{if (CheckForInternetConnection()){Isconnected true;}else{Isconnected false;}
}Jeshurunandroid 手机也有检测 WIFI 连通性的代码它非常高效的抓取 Google 首页相应的 java 代码如下public static boolean hasInternetAccess(Context context) {if (isNetworkAvailable(context)) {try {HttpURLConnection urlc (HttpURLConnection) (new URL(http://clients3.google.com/generate_204).openConnection());urlc.setRequestProperty(User-Agent, Android);urlc.setRequestProperty(Connection, close);urlc.setConnectTimeout(1500); urlc.connect();return (urlc.getResponseCode() 204 urlc.getContentLength() 0);} catch (IOException e) {Log.e(TAG, Error checking internet connection, e);}} else {Log.d(TAG, No network available!);}return false;
}转成 C# 代码的话大概如下var request (HttpWebRequest)WebRequest.Create(http://g.cn/generate_204);
request.UserAgent Android;
request.KeepAlive false;
request.Timeout 1500;using (var response (HttpWebResponse)request.GetResponse())
{if (response.ContentLength 0 response.StatusCode HttpStatusCode.NoContent){//Connection to internet available}else{//Connection to internet not available}
}点评区 这个功能在带 GUI 的程序中大多属于刚需功能 ping 判断连通性是一个好办法学习了。