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.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格