首页 > 解决方案 > TCP 客户端未正确接收数据 VB.NET

问题描述

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

服务器逻辑:服务器端是用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

消息框 1 收到字符串

消息框 2 空白弹出窗口?

如何不获取空白消息框。即使进行比较,接收到的数据也不匹配参数。尝试使用延迟,尝试将缓冲区大小固定为 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

标签: vb.netsocketsclient-servertcpclient

解决方案


推荐阅读