使用VB.Net 2015发送十六进制字节的简单TCP客户端程序
我尝试使用VB.net通过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
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
,因为它用于内部缓冲区。您应该始终自行决定缓冲区大小
NetworkStream.Read()
中的返回值来确定读取了多少
然后,您需要阅读Modbus文档,查看其数据是否包含指示数据包结束或长度的内容