2012-04-24 314 views
2

タイマーを実行して切断された接続をチェックするには、TCP KeepAliveを実装します。TCPクライアント(ソケット)でVB KeepAliveをVB.NETで実装する方法

私の場合、私はTCPクライアント(ソケットクラスを使用しています)とサードパーティ製サーバー(私はそれを制御していません)を持っています。 接続状態を確認するためにTCPクライアントでTCPキープアライブを使用するにはどうすればよいですか?

私は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のでチェックしていると私は送信されたパッケージを気づきました。

関連する問題