dongmou5628 2013-11-20 03:01
浏览 403
已采纳

golang:ioutil.ReadAll()的网络响应为空,对等体重置连接

I'm trying to test out performing a simple TCP MODBUS read of a single register from a device emulator. When running the code it is showing a response of 0 bytes and I get the message "connection reset by peer". Any ideas as to why it's not working?

UPDATE, my request was incorrect, the correct working MODBUS TCP poll code is:

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("
")
}
  • 写回答

1条回答 默认 最新

  • dtz8044 2013-11-20 21:18
    关注

    Originally I thought that fmt.Fprintf may be changing the request data on the way out, but this example seems to work OK.

    However, I would still recommend using the lower-level Write/Read instead of 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于#flink#的问题:关于docker部署flink集成hadoop的yarn,请教个问题flink启动yarn-session.sh连不上hadoop
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题