doushang2571 2018-08-16 22:08
浏览 66
已采纳

如何确定golang中连接的确切字节长度?

I have the following code:

var buf []byte
read_len, err := conn.Read(buf)
if err != nil {
    fmt.Println("Error reading:", err.Error())
}
buffer := make([]byte, read_len)
_, err = conn.Read(buffer)
if err != nil {
    fmt.Println("Error reading:", err.Error())
}

The intention was to determine read_len with the first buf, then create a second buffer which is the exact length of an incoming json request. This just results in an error

unexpected end of JSON input

When I try to unmarshal

var request Device_Type_Request_Struct
err = json.Unmarshal(buffer, &request)

I'm assuming that this error occurs because the conn.Read(buffer) is returning nothing because another buffer has already read it (not sure though). How should I go about determining the length of json request while also being able to read it into a buffer (of the exact same length)?

  • 写回答

1条回答 默认 最新

  • douwen3083 2018-08-16 22:22
    关注

    Read returns the number of bytes read to the buffer. Because the length of the buffer passed to the first call to conn.Read is zero, the first call to conn.Read always returns zero.

    There is no way to determine how much data a peer has sent without reading the data.

    The easy solution to this problem is to use the JSON decoder:

    d := json.NewDecoder(conn)
    var request Device_Type_Request_Struct
    if err := d.Decode(&request); err != nil {
        // handle error
    }
    

    The decoder reads and decodes JSON values from a stream.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突