作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想实现TCP KeepAlive,以便通过运行计时器检查断开的连接。
就我而言,我有一个TCP客户端(使用套接字类)和一个第三方服务器(我对此没有控制权)。
如何在我的TCP客户端上使用TCP KeepAlive来检查连接状态?
目前,我已启用TCP KeepAlive选项!
tcpsocket.Connect(IPEndPoint)
tcpSocket.SetSocketOption(SocketOptionLevel.Tcp,SocketOptionName.KeepAlive,1);
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
最佳答案
最后,我设法使用了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
关于.net - 如何在TCP Client(socket)上的VB.NET中实现TCP KeepAlive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10292593/
我是一名优秀的程序员,十分优秀!