I'm encountering a problem when I try to write over a network stream.

When I press this button here, I can successfully write to the tcp stream and the other part of the program successfully receives the data.

Dim ClientSocket As TcpClient

Private Sub btnConnect_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnConnect.MouseClick

      ClientSocket = New TcpClient

      ClientSocket.Connect(frmNetworkSettings.txtServerIPAddress.Text, CInt(frmNetworkSettings.txtFileSharingPort.Text))

      Dim NetworkStream As NetworkStream = ClientSocket.GetStream()

      If NetworkStream.CanRead And NetworkStream.CanWrite Then

             Dim SentData As Byte()

             SentData = Encoding.ASCII.GetBytes(Username & Chr(32) & "is connected." & Environment.NewLine)

             NetworkStream.Write(SentData, 0, SentData.Length())

             NetworkStream.Flush()

      End If

End Sub

But when I press this button below, after pressing the button above, I cannot write on the tcp network stream and the other program on the network receives no data.

Private Sub btnDisconnect_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnDisconnect.MouseClick

     Dim NetworkStream As NetworkStream = ClientSocket.GetStream()

     If NetworkStream.CanRead And NetworkStream.CanWrite Then

            Dim SentData As Byte()

            SentData = Encoding.ASCII.GetBytes(Username & Chr(32) & "is disconnected." & Environment.NewLine)

            NetworkStream.Write(SentData, 0, SentData.Length())

            NetworkStream.Flush()

     End If

End Sub

Thanks in advance!

Recommended Answers

All 3 Replies

try declaring NetworkStream with class level scope the same as ClientSocket and use the same stream in both subs.

Ok. I'll get you updated.

I figured out the problem. Its because I'm reading the network stream only during a connection is made. I should modify my code to read the network stream after a connection is made. Anyway, thanks for your reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.