vb.net - 使用 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:
解决方案
数据在那里,但您看不到它,因为它以空字节(&H0
或仅0
)开头。大多数遇到空字节的文本控件将其解释为字符串的结尾,因此不会呈现文本的其余部分。
GetString()
仅按原样获取字节并将它们转换为具有相同值的相应字符。将结果转换为可读格式取决于您。
解决方案是跳过GetString()
并改为迭代数组,将每个字节转换为十六进制或数字字符串。
此外,还有两件非常重要的事情:
您不应该
TcpClient.ReceiveBufferSize
在代码中使用它,因为它用于内部缓冲区。您应该始终自行决定缓冲区大小。由于 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
推荐阅读
- regex - 与边界结合时,正则表达式后视无法按预期工作
- arrays - 为什么当元素明显受到约束时,Swift 编译器在推断我的通用元素的类型时会抛出错误?
- angular - 如果只有一个,则调用该函数
- java - 单个 URL Web 应用程序中文件夹和子文件夹的“返回”按钮
- python-3.x - 在 tkinter 主循环中打印所有 pygame 事件
- vba - 如何按两个不同的列对 Excel 工作表进行排序
- python - TypeError: buf 不是数字元组
- docker - 有多少参数可以通过 cli 传递给 docker 入口点
- java - 我在哪里可以下载 Oracle Spatial 11g Java API?
- python - 在python中将文本文件转换为json