首页 > 解决方案 > 使用 VB.Net 2015 发送十六进制字节的简单 TCP 客户端程序

问题描述

我尝试使用 VB.net 通过 TCP 发送十六进制字节。并接收数据的响应。

以下我使用的代码,

    Dim tcpClient As New System.Net.Sockets.TcpClient()
    tcpClient.Connect("192.168.1.10", 502)
    Dim networkStream As NetworkStream = tcpClient.GetStream()


    If networkStream.CanWrite And networkStream.CanRead Then
        ' Do a simple write.
        Dim sendBytes As [Byte]() = {&H0, &H4, &H0, &H0, &H0, &H6, &H5, &H3, &HB, &HD3, &H0, &H1}
        networkStream.Write(sendBytes, 0, sendBytes.Length)
        ' Read the NetworkStream into a byte buffer.
        Dim bytes(tcpClient.ReceiveBufferSize) As Byte
        networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
        ' Output the data received from the host to the console.
        Dim returndata As String = Encoding.ASCII.GetString(bytes)
        TextBox1.Text = ("Host returned: " + returndata)
    Else
        If Not networkStream.CanRead Then
            TextBox1.Text = "cannot not write data to this stream"
            tcpClient.Close()
        Else
            If Not networkStream.CanWrite Then
                TextBox1.Text = "cannot read data from this stream"
                tcpClient.Close()
            End If
        End If
    End If

当我发送sendbytes数据时,我没有收到任何数据。当我发送数据时,master会自动向我发送数据,但我没有收到任何数据。这是 Modbus 通信。

我只能看到Host returned:

标签: vb.net

解决方案


数据在那里,但您看不到它,因为它以空字节(&H0或仅0)开头。大多数遇到空字节的文本控件将其解释为字符串的结尾,因此不会呈现文本的其余部分。

GetString()仅按原样获取字节并将它们转换为具有相同值的相应字符。将结果转换为可读格式取决于您。

解决方案是跳过GetString()并改为迭代数组,将每个字节转换为十六进制或数字字符串。

此外,还有两件非常重要的事情:

  1. 您不应该TcpClient.ReceiveBufferSize在代码中使用它,因为它用于内部缓冲区。您应该始终自行决定缓冲区大小。

  2. 由于 TCP 是基于流的协议,因此应用层没有数据包的概念。来自服务器的一次“发送”通常不等于一次“接收”。您可能会收到比第一个数据包实际数据更多或更少的数据。使用 from 的返回值NetworkStream.Read()来确定已读取了多少。

    然后,您需要阅读 Modbus 文档并查看其数据是否包含指示数据包结束或长度的内容。

'Custom buffer: 8 KB.
Dim bytes(8192 - 1) As Byte
Dim bytesRead As Integer = networkStream.Read(bytes, 0, bytes.Length)

Dim returndata As String = "{"

'Convert each byte into a hex string, separated by commas.
For x = 0 To bytesRead - 1
    returnData &= "0x" & bytes(x).ToString("X2") & If(x < bytesRead - 1, ", ", "}")
Next

TextBox1.Text = "Host returned: " & returnData

推荐阅读