我正在尝试测试从设备模拟器执行单个寄存器的简单 TCP MODBUS 读取。运行代码时,它显示 0 字节的响应,我收到消息“连接由对等方重置”。关于为什么它不起作用的任何想法?
更新,我的请求不正确,正确的工作 MODBUS TCP 轮询代码是:
package main
import (
"fmt"
"net"
)
// TCP MODBUS client
func main() {
conn, err := net.Dial("tcp", "192.168.98.114:502")
if err != nil {
fmt.Println(err)
}
numRegs := 1
# make a MODBUS TCP request (be careful, the format is different to MODBUS serial)
request := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x01, 0x00, 0x01}
n, err := conn.Write(request)
if err != nil {
fmt.Println(err)
}
expectedResponseLen := 5 + 2 * numRegs
response := make([]byte, expectedResponseLen)
n, err = conn.Read(response)
conn.Close()
if err != nil {
fmt.Println(err)
}
for i := 0; i < n; i++ {
fmt.Printf("%02x ", response[i])
}
fmt.Println("\n")
}
最佳答案
本来我以为fmt.Fprintf
可能在出路的时候改变了请求数据,但是this example似乎工作正常。
但是,我仍然建议使用较低级别的 Write/Read
而不是 fmt.Fprintf/ioutil.ReadAll
:
req := []byte { 0x01, 0x03, 0x00, 0x01, 0x00, 0x01, 0xd5, 0xca }
n, err := conn.Write(req)
if err != nil {
fmt.Println("write error:", err)
return
}
fmt.Printf("wrote %d bytes for request: %#v", n, req)
rsp := make([]byte, 64)
n, err = conn.Read(rsp)
fmt.Printf("received %d bytes in response: %#v", n, rsp[:n])
if err != nil {
fmt.Println("read error:", err)
}
关于networking - golang : network response from ioutil. ReadAll() 为空,连接被对端重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20086504/