我已经构建了一个dll,如果我们有互联网则返回true,否则返回false。 我们执行以下操作: 1.调用ping我们的服务器,如果失败则尝试下一步 2.将http请求调用到我们的一个WCF API http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat
这是在胜利服务中完成的。
在PC和一些服务器(Windows服务器2k R2)中,它一直工作几天没有问题,每2分钟我们醒来并测试连接。
但是,在Azure虚拟机中,它传递了几次然后失败了,为什么?
我们在网络浏览器中尝试过: http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat 看到结果,我们每秒点击刷新2分钟,看看它永远不会失败。
但是从我们的WinService做同样的事情几次失败后,开始获取超时!!!!
我们不知道为什么,看起来像防火墙,但为什么它不会在刷新时阻止浏览器!!!
这里我们在.Net做了什么:
private static bool IsConnectedToInternetHttpRequest(string url = "http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat")
{
//GET http://db.OurDomainName.com/WCFService.svc/GetCurrentTimeUnixFormat HTTP/1.1
//Host: db.tako.com
//Connection: keep-alive
//Cache-Control: max-age=0
//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
//User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
//Accept-Encoding: gzip,deflate,sdch
//Accept-Language: en-US,en;q=0.8
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = (int)new TimeSpan(0, 0, 30).TotalMilliseconds;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36";
request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Refresh);
request.KeepAlive = true;
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return true;
}
else
{
return false;
}
}
catch (Exception )
{
return false;
}
}
答案 0 :(得分:1)
public Contructor(){
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += new System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
//connected
}
else
{
//disconnected
}
}
答案 1 :(得分:0)
[DllImport("wininet.dll", SetLastError = true)]
static extern bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved);
const int FLAG_ICC_FORCE_CONNECTION = 1;
bool internetStatus = false;
if (InternetCheckConnection("http://www.google.com", FLAG_ICC_FORCE_CONNECTION, 0) ||
InternetCheckConnection("http://www.microsoft.com", FLAG_ICC_FORCE_CONNECTION, 0) ||
InternetCheckConnection("http://www.facebook.com", FLAG_ICC_FORCE_CONNECTION, 0))
{
internetStatus = true;
}