2009-12-26 145 views

回答

5

就是這樣。實質上,這是來自2005年1月12日的MSDN提示和技巧網絡廣播。它被稍微改寫以符合我自己的標準,並且完全未經測試,但您明白了。隨你便便使用。

enum ConnectionStatus 
{ 
    Offline, 
    OnlineTargetNotFound, 
    OnlineTargetFound, 
} 

ConnectionStatus GetConnectionStatus(String url) 
{ 
    try 
    { 
     // 
     // If the device is set to loopback, then no connection exists. 
     // 
     String hostName = System.Net.Dns.GetHostName(); 
     System.Net.IPHostEntry host = System.Net.Dns.GetHostByName(hostName); 
     String ipAddress = host.AddressList.ToString(); 

     if(ipAddress == System.Net.IPAddress.Parse("127.0.0.1").ToString()) 
     { 
      return ConnectionStatus.Offline; 
     } 

     // 
     // Now we know we're online. Use a web request and check 
     // for a response to see if the target can be found or not. 
     // N.B. There are blocking calls here. 
     // 
     System.Net.WebResponse webResponse = null; 
     try 
     { 
      System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url); 
      webRequest.Timeout = 10000; 
      webResponse = webRequest.GetResponse(); 

      return ConnectionStatus.OnlineTargetFound; 
     } 
     catch(Exception) 
     { 
      return ConnectionStatus.OnlineTargetNotFound; 
     } 
    } 
    catch(Exception) 
    { 
     return ConnectionStatus.Offline; 
    } 
} 
+0

感謝您的示例。它工作正常,除了我得到一個非常奇怪的間歇性問題。最後通過在「finally」塊中敲擊來修復它:webRequest = null; webResponse.Close(); webResponse = null; – 2011-05-31 03:10:18

1

這是一段源自同一網絡廣播的代碼。用法應該非常簡單。儘管它可以作爲網絡監視器,在檢測到連接可用性時通知您,但您可以選擇僅提取IsUrlAvailable函數。

 
using System; 
using Microsoft.WindowsMobile.Status; 
using System.IO; 
using System.Net; 
using System.Windows.Forms; 
using System.Threading; 

namespace RAMIS2.Classes { 
    class NetworkWatcher : IDisposable { 

     public delegate void NetworkStatusDeterminedDelegate(bool remoteServerReachable, bool internetReachable); 
     public event NetworkStatusDeterminedDelegate NetworkStatusDetermined; 

     SystemState nw = null; 
     const string _remoteServerExpectedText = @"RAMIS"; 
     Uri InternetUrl = new Uri(@"http://www.google.com"); 
     const string _internetReachableExpectedText = @"Google"; 

     const int sleepTimeBetweenConnectTries = 15000; 
     const int maxConnectTryCount = 2; 
     Uri _remoteServerUrl = new Uri("https://demo.mywebsite.com/test.txt"); 

     bool internetReachable; 
     bool remoteServerReachable; 

     Thread bgw; 

     public void Dispose() { 
      if (bgw != null) { bgw.Abort(); bgw = null; } 
      if (nw != null) { nw.Changed -= NetworkWatcher_Changed; nw.Dispose(); nw = null; } 
     } 

     Control invoke_ctrl; 
     public NetworkWatcher() { 
      invoke_ctrl = new Control(); 
     } 

     public void Start() { 
      // This only works for Windows Mobile 5.0 and higher, not PPC 2003 
      if (Environment.OSVersion.Version >= new Version(5, 0)) { 
       nw = new SystemState(SystemProperty.ConnectionsCount, false); 
       nw.Changed += new ChangeEventHandler(NetworkWatcher_Changed); 
      } 
      bgw = new Thread(DetermineNetworkState); 
      bgw.Start(); 
     } 

     void NetworkWatcher_Changed(object sender, ChangeEventArgs args) { 
      // instantly test new connection status 
      if (bgw != null) DetermineNetworkState(); 
     } 

     public bool IsUrlReachable(Uri url, string expectedText) { 
      bool isUrlReachable = false; 
      HttpWebRequest httpRequest = null; 
      HttpWebResponse httpResponse = null; 
      Stream responseStream = null; 
      StreamReader responseReader = null; 

      for (int connectTryCount = 0; 
       !isUrlReachable && connectTryCount = 0; 
       } 
       catch (SystemException) { } 
       finally { 
        if (responseReader != null) responseReader.Close(); 
        if (responseStream != null) responseStream.Close(); 
        if (httpResponse != null) httpResponse.Close(); 
       } 
       if (!isUrlReachable) Thread.Sleep(sleepTimeBetweenConnectTries); 
      } 
      return isUrlReachable; 
     } 

     void DetermineNetworkState() { 
      try { 
       while (true) { 
        if (Environment.OSVersion.Version >= ST.WM5.Version) DetermineNetworkStateInternal(SystemState.ConnectionsCount); 
        else DetermineNetworkStateInternal(1); 
        // invoke on GUI thread 
        invoke_ctrl.BeginInvoke(new NetworkStatusDeterminedDelegate(NetworkStatusDetermined), remoteServerReachable, internetReachable); 
        Thread.Sleep(sleepTimeBetweenConnectTries); 
       } 
      } 
      catch (ThreadAbortException) { } 
     } 

     void DetermineNetworkStateInternal(int connectionsCount) { 
      if (connectionsCount > 0) { 
       remoteServerReachable = IsUrlReachable(_remoteServerUrl, _remoteServerExpectedText); 
       internetReachable = remoteServerReachable ? true : 
        IsUrlReachable(InternetUrl, _internetReachableExpectedText); 
      } 
      else remoteServerReachable = internetReachable = false; 
     } 

    } 
}