ClientSocket / NetworkStream Connect and Disconnect

Ian W

Active member
Joined
Feb 11, 2010
Messages
31
Programming Experience
1-3
I have a app that connects to a networked device, I send and receive data to and from this device using a NetStream.

The code I have to do this I found in an example and its fine for what I needed at the time but I want to update it now so I can force a disconnect so I can release the socket and reconnect if I wish (as I can't now).

I currently use this following code to connect to my device.

VB.NET:
    Private Function POE_Connect() As Boolean
        Dim PoE_IP As String ' = "192.168.33.85"
        Dim PoE_Port As Integer = 10003

        PoE_IP = "192.168.33." & IP4.Text

        POE_Connect = True

        If My.Computer.Network.Ping(PoE_IP) Then
            Try
                clientSocket.Connect(PoE_IP, PoE_Port)
                If clientSocket.Connected Then
                    netStream = clientSocket.GetStream()
                End If
            Catch ex As Exception
                Me.Status_Display.Text = ("Connection Failed - Reset Box")
                POE_Connect = False
                Exit Function
            End Try
        Else
            Me.Status_Display.Text = ("Ping request timed out, unit plugged in?")
            POE_Connect = False
            Exit Function
        End If

    End Function

The problem I am having is that when I want to disconnect I use:
VB.NET:
netstream.dispose
clientsocket.close

This appears to shutdown the connect however when I try to reconnect I get.

"Cannot access a disposed object. Object name: 'System.Net.Sockets.TcpClient'."

How can I go about rewriting my code so it allows me to gracefully shutdown all connections to the device?
 
This appears to shutdown the connect
Correct.
however when I try to reconnect I get.
"Cannot access a disposed object
You can't reconnect with the same TcpClient object that was closed, create a new TcpClient object.
VB.NET:
clientSocket = New TcpClient
 
Back
Top