无法通过TCP网络流写入

时间:2013-01-09 19:33:29

标签: .net vb.net tcpclient networkstream

当我尝试通过网络流进行写操作时遇到问题。

当我在这里按下此按钮时,我可以成功写入tcp流,程序的其他部分成功接收数据。

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

但是当我按下下面的按钮时,按下上面的按钮后,我无法在tcp网络流上写入,而网络上的其他程序也没有收到任何数据。

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

其他详细信息:

这是接收其他程序数据的部分。

Private Sub ConnectionTimer_Tick(sender As Object, e As System.EventArgs) Handles ConnectionTimer.Tick

    Try

        If Listener.Pending Then

            ClientSocket = Listener.AcceptTcpClient

            Dim ByteData(ClientSocket.ReceiveBufferSize) As Byte

            Dim NetworkStream As NetworkStream = ClientSocket.GetStream

            Dim LogMessage As String = String.Empty

            NetworkStream.Read(ByteData, 0, CInt(ClientSocket.ReceiveBufferSize))

            LogMessage = Encoding.ASCII.GetString(ByteData)

            DisplayLogMessage(LogMessage)

        End If

    Catch ex As Exception

        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)

    End Try

End Sub

提前致谢!

1 个答案:

答案 0 :(得分:0)

我弄明白了这个问题。这是因为我只是在建立连接时才读取网络流。我应该修改我的代码,以便在建立连接后读取网络流。