近一周我正在阅读并试图找到使用TCP客户端检查连接状态的解决方案(使用套接字类) 在我的情况下,我有一个连接到服务器的TCP客户端(它不受我控制),我不时要检查连接状态,并在必要时重新连接。 我已经阅读了很多互联网上的信息,但我没有找到合适的解决方案。如何在VB.NET中使用TCP客户端检查TCP服务器(套接字)的连接状态
简而言之,这些是我在互联网上找到并尝试实施的方法。 但是不幸的是,我发现了一些TCP服务器关闭的情况,TCP客户端仍在说连接
请问有人遇到过这个问题可以帮我吗?使用轮询
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,采用轮询
从MSDNPrivate 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.Example
1.Example
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
原则上没有可靠的方法来知道连接是否仍然可用而不从远程端接收值。中间的网络可能只是一个黑洞,你永远不知道没有收到什么东西。 – usr 2014-10-08 07:56:33