2016-08-30 35 views
0

我在vb.net上寫有一個windows服務,每隔幾秒10secs或更多它將檢查我是否有連接到webservice鏈接,如果我那麼生病發送一些數據到那個webservice。我不會總是有數據發送,但無論我想在我嘗試發送任何內容之前檢查是否有連接,並且在這種情況下,病人都不知道該服務是否已啓動。 我的問題是,2-3次嘗試後連接檢查給我'連接超時'。經常檢查連接到webservice

這裏是我使用的代碼:

Public Function HaveInternetConnection() As Boolean 
     HaveInternetConnection = False 
     Try 
      Dim request As HttpWebRequest = HttpWebRequest.Create(My.Settings.WebServiceLink) 
      request.Timeout = 15000 

      Dim response As HttpWebResponse = request.GetResponse 

      If response.StatusCode = HttpStatusCode.OK Then 
       HaveInternetConnection = True 
      End If 
     Catch ex As Exception 
      Return False 
     End Try 

我試圖改變超時時間,但沒有運氣。 我也嘗試在每個時間間隔上創建一個新的'Private ws As New webservice',並且在服務啓動時不創建1個新的webservice,但又沒有運氣。

有沒有更簡單的方法來檢查每隔幾秒鐘,如果我有一個連接到web服務?

預先感謝您

回答

0

您的代碼看起來不錯,所以如果你超時錯誤也可能是一些其他原因。

要只檢查連接到可對其進行ping一臺主機,節省你的CPU時間來創建一個HTTPWebRequest

例子:

If My.Computer.Network.IsAvailable Then 
    'this only tells that the PC is connected to a network 
    'doesn't really mean that there is internet access! 
    Try 
     My.Computer.Network.Ping("yourhost") 
     'here the host has answered the ping request 
     Catch ex As System.Net.NetworkInformation.PingException 
     'the ping has failed. your host is unreachable 
     End Try 
End If 

測試是否有可用的網絡從產生節省CPU一個例外(重操作)的情況下,電腦脫機

+0

我試圖從cmd ping web服務鏈接,我得到錯誤'Ping請求找不到主機'。 我的鏈接以「http:// something.something.gr/service/service.asmx」開頭 –

+0

嘗試指定一個端口,如https://msdn.microsoft.com/zh-CN/library/he5sca5t (v = vs.90).aspx – theBugger

+0

這篇文章對theBugger不是很有幫助。我仍然遇到異常 'Ping請求期間發生異常。' –