2012-04-24 63 views
2

我想實現TCP KeepAlive以通過運行計時器來檢查丟棄的連接。在我的情況下,我有一個TCP客戶端(使用套接字類)和第三方服務器(我沒有控制它)。 如何在我的TCP客戶端上使用TCP KeepAlive以檢查連接狀態?如何在TCP客戶端(套接字)上實現VB.NET中的TCP KeepAlive

目前我已啓用TCP KeepAlive選項!

tcpsocket.Connect(IPEndPoint) 
tcpSocket.SetSocketOption(SocketOptionLevel.Tcp,SocketOptionName.KeepAlive,1); 

搜索互聯網上我發現這個過程,應該工作,但我想知道如何我可以用它在我的TCP客戶端?

Private Shared Function SetKeepAlive(ByRef tcpSocket As Socket, ByVal keepAliveTime As UInteger, ByVal keepAliveInterval As UInteger) As Boolean 
    ' Pack three params into 12-element byte array; not sure about endian issues on non-Intel 
    Dim SIO_KEEPALIVE_VALS(11) As Byte 
    Dim keepAliveEnable As UInteger = 1 
    If (keepAliveTime = 0 Or keepAliveInterval = 0) Then keepAliveEnable = 0 
    ' Bytes 00-03 are 'enable' where '1' is true, '0' is false 
    ' Bytes 04-07 are 'time' in milliseconds 
    ' Bytes 08-12 are 'interval' in milliseconds 
    Array.Copy(BitConverter.GetBytes(keepAliveEnable), 0, SIO_KEEPALIVE_VALS, 0, 4) 
    Array.Copy(BitConverter.GetBytes(keepAliveTime), 0, SIO_KEEPALIVE_VALS, 4, 4) 
    Array.Copy(BitConverter.GetBytes(keepAliveInterval), 0, SIO_KEEPALIVE_VALS, 8, 4) 

    Try 
    Dim result() As Byte = BitConverter.GetBytes(CUInt(0)) ' Result needs 4-element byte array? 
    tcpSocket.IOControl(IOControlCode.KeepAliveValues, SIO_KEEPALIVE_VALS, result) 
    Catch e As Exception 
    Return False 
    End Try 
    Return True 
End Function 

任何幫助,將不勝感激。

PS:我是編程新手,請原諒我的編碼錯誤。

回答

2

最後,我設法使用TCP KeepAlive。 因此,爲了實現這一點,我剛剛叫mainform_load程序:

 tcpSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) 
     tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, True) 
     SetKeepAlive(tcpSocket, keepalivetime, keepaliveinterval) 
     Try 
      tcpSocket.Connect(ipEndPoint) 
     Catch e As SocketException 
      ... 
     End Try 

我已使用Wireshark檢查,我注意到了發送的數據包。