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 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像