0

当我尝试通过网络流写入时遇到问题。

当我在这里按下这个按钮时,我可以成功写入 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

提前致谢!

4

1 回答 1

0

我解决了这个问题。这是因为我仅在建立连接期间才读取网络流。建立连接后,我应该修改我的代码以读取网络流。

于 2013-01-11T04:24:13.123 回答