【问题标题】:How to implement TCP KeepAlive in VB.NET on a TCP Client(socket)如何在 TCP 客户端(套接字)上在 VB.NET 中实现 TCP KeepAlive
【发布时间】:2012-05-04 18:37:12
【问题描述】:

我想实现 TCP KeepAlive,以便通过运行计时器来检查断开的连接。

就我而言,我有一个 TCP 客户端(使用套接字类)和一个第三方服务器(我无法控制它)。 如何在我的 TCP 客户端上使用 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:我是编程新手,所以请原谅我的编码错误。

【问题讨论】:

    标签: .net vb.net sockets tcpclient keep-alive


    【解决方案1】:

    最后我设法使用了 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 核对过,我注意到已发送的包裹。

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 2012-05-04
      • 2012-03-29
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 2019-02-07
      • 2012-06-24
      相关资源
      最近更新 更多