近一个星期以来,我正在阅读并试图找到使用 TCP 客户端(使用套接字类)检查连接状态的解决方案在我的场景中,我有一个连接到服务器的 TCP 客户端(它不受我控制),我希望不时检查连接状态,并在必要时重新连接。我在互联网上阅读了很多信息,但我没有找到合适的解决方案。
简而言之,这些是我在互联网上找到并尝试实施的方法。但不幸的是,我发现了一些 TCP 服务器关闭并且 TCP 客户端仍然说已连接的情况
我可以请遇到此问题的人帮助我吗?
1.示例来自 MSDN
Private Function IsConnected(tcpSocket As Socket) As Boolean
Dim blockingState As Boolean = tcpSocket.Blocking
IsConnected = False
Try
Dim tmp(0) As Byte
tcpSocket.Blocking = False
tcpSocket.Send(tmp, 0, 0)
Return True
Catch e As SocketException
If e.NativeErrorCode.Equals(10035) Then
Return True
Else : Return False
End If
ThrowError(e)
Finally
tcpSocket.Blocking = blockingState
End Try
End Function
2.使用投票的例子
Function Connected() As Boolean
Connected = False
If (tcpSocket.Connected) Then
If ((tcpSocket.Poll(0, SelectMode.SelectWrite)) AndAlso (Not tcpSocket.Poll(0, SelectMode.SelectError))) Then
Dim b As Byte() = New Byte(1) {}
If tcpSocket.Receive(b, SocketFlags.Peek) = 0 Then
Return False
Else : Return True
End If
Else
Return False
End If
Else
Return False
End If
End Function
3.使用投票
Private Function Connect2() As Boolean
Connect2 = False
If tcpSocket.Poll(0, SelectMode.SelectRead) = True Then
Dim byteArray As Byte() = New Byte(1) {}
If (tcpSocket.Receive(byteArray, SocketFlags.Peek)) = 0 Then Connect2 = True
End If
Return Connect2()
End Function