Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用VB.Net 2015发送十六进制字节的简单TCP客户端程序_Vb.net - Fatal编程技术网

使用VB.Net 2015发送十六进制字节的简单TCP客户端程序

使用VB.Net 2015发送十六进制字节的简单TCP客户端程序,vb.net,Vb.net,我尝试使用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 networkS

我尝试使用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通信


我只能看到主机返回的数据:

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

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

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

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

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

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

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

  • 自定义缓冲区:8KB。 Dim字节(8192-1)作为字节 Dim bytesRead As Integer=networkStream.Read(字节、0、字节、长度) Dim returndata作为字符串=“{” '将每个字节转换为十六进制字符串,用逗号分隔。 对于x=0到字节读取-1 returnData&=“0x”和字节(x).ToString(“X2”)和If(x回答得很好,伙计!