TCP客户端无法正确接收数据VB.NET

时间:2018-11-19 15:53:02

标签: vb.net sockets client-server tcpclient

我正在尝试创建一个简单的客户端应用程序来接收小文本数据,将其进行比较,然后根据发送的服务器在客户端计算机上执行某些操作。

服务器逻辑:服务器端是用Java制作的,因此无法在其中进行任何更改。服务器在连接到客户端时发送字符串“ abc001”。

客户端逻辑:客户端从服务器接收到字符串“ abc001”,并检查接收到的字符串是否与“ abc001”相同,然后相应地执行操作。

问题:当客户端收到数据时,我将其显示在msgbox中。但是,不仅会弹出“ abc001”,还会弹出一个额外的空白msgbox(包含图片)。

客户代码-开始时

    Try
        ' declare vals
        Dim ip As String = "127.0.0.1"
        Dim port As Integer = 5000

        ' set client
        _client = New TcpClient(ip, port)

        ' disable cross thread calls checking
        CheckForIllegalCrossThreadCalls = False

        ' recieve msg
        Threading.ThreadPool.QueueUserWorkItem(AddressOf RecieveMessages)
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

客户代码-接收数据

Private Sub RecieveMessages(state As Object)
        Try
            While True
                Dim ns As NetworkStream = _client.GetStream()
                Dim toRecieve(_client.ReceiveBufferSize) As Byte
                ns.Read(toRecieve, 0, CInt(_client.ReceiveBufferSize))
                Dim txt As String = Encoding.ASCII.GetString(toRecieve)
                MsgBox(txt)
            End While
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

MsgBox 1 String Recieved

MsgBox 2 Blank Popup?

如何不获取空白msgbox。即使进行比较,接收的数据也不匹配参数。尝试使用延迟,尝试将缓冲区大小固定为6个字节,但没有使用。谢谢。

编辑1 :尽我所能找出来了,但无法解决。尝试清理返回的字符串数据,甚至尝试将每个返回数据存储在数组中。看到堆栈,并说msgbox中没有任何内容。它是空的。我什至都不知道该怎么办。这是干净的字符串的代码:

Private Sub RecieveMessages(state As Object)
        Dim message(0) As String
        Dim command_raw, command_clean, command As String
        Dim counter As Integer = 0
        Try
            While True
                Dim ns As NetworkStream = _client.GetStream()
                Dim toRecieve(_client.ReceiveBufferSize) As Byte
                ns.Read(toRecieve, 0, CInt(_client.ReceiveBufferSize))
                Dim txt As String = Encoding.ASCII.GetString(toRecieve)
                message(0) = txt
                command_raw = message(0)
                command_clean = command_raw.Replace(vbCrLf, Nothing)
                command = command_clean.Substring(0, 6)
                MsgBox(command)
            End While

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

0 个答案:

没有答案