tcpclient does not recognize socket state.

groadsvb

Well-known member
Joined
Nov 13, 2006
Messages
75
Programming Experience
Beginner
I have a service that uses the tcpClient to send and receive data. I can unplug the network cable and the service does not know the connection has been broken. This is the code that is used to test the connection. The call to send does not throw an error.

       Private Function IsConnected() As Boolean
            SyncLock (_sendSyncObject)
                If Not _tcpClient Is Nothing Then
                    Try
                        If IsConnectionInCloseWait() Then Return False
                        Dim data() As Byte = {}
                        _tcpClient.Client.Blocking = False
                        _tcpClient.Client.Send(data, 0, 0)
                        Return True
                    Catch ex As SocketException
                        ' 10035 == WSAEWOULDBLOCK
                        If ex.NativeErrorCode.Equals(10035) Then Return True
                    Catch e As Exception
                        Return False
                    Finally
                        If Not _tcpClient Is Nothing AndAlso Not _tcpClient.Client Is Nothing Then _tcpClient.Client.Blocking = True
                    End Try
                End If
            End SyncLock
            Return False
        End Function
 
With some subtle differences the code is similar to the example posted here: Socket.Connected Property (System.Net.Sockets)

You should be able to detect unplugged network cable in local computer immediately with My.Computer.Network.IsAvailable property, this is checking the operational status of the network interfaces.
 
Hey JohnH,
That seems to be the key. Before the application can recognize the lost connection there had to be an attempt to actually write something. Thanks.
 

Latest posts

Back
Top