Operagust
Operagust

Reputation: 147

How to implement TCP KeepAlive in VB.NET on a TCP Client(socket)

I want to implement the TCP KeepAlive in order to check dropped connections by running a timer.

In my case, I have a TCP Client (using socket class) and a third party server (i have no control on it). How can i use the TCP KeepAlive on my TCP Client in order to check the connection state?

For the moment i have enabled the TCP KeepAlive option!

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

Searching on the internet i have found this procedure that should work but i am wondering how can i use it in my TCP Client?

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

Any help would be appreciated.

PS: I am new in programming so please excuse me my coding mistakes.

Upvotes: 2

Views: 8783

Answers (1)

Operagust
Operagust

Reputation: 147

Finally i managed to use the TCP KeepAlive. So in order to implement this i've just called in the mainform_load procedure :

        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

I have checked with WireShark and i've noticed the sent packages.

Upvotes: 2

Related Questions