【发布时间】:2013-12-03 21:19:38
【问题描述】:
我正在尝试测试从设备仿真器中对单个寄存器执行简单的 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")
}
【问题讨论】:
-
这似乎是与网络相关的问题,而不是您的代码问题。
connection reset by peer可能是由于没有人在该端口上侦听或服务由于某种原因未接听您的电话。你检查了吗? -
connection reset by peer通常表示客户端接受了连接,但在收到您的请求后挂断了。也许请求是错误的? (另外,我认为你的意思是使用fmt.Fprint) -
谢谢汤姆,我的请求格式错误,现在上面是正确的代码。
标签: networking tcp go modbus