doupuzhimuhan9216 2018-06-20 16:39
浏览 58
已采纳

如果没有EOF,从Golang中的服务器读取Unix套接字响应的最佳方法是什么?

I want to read full response from the server, but I don't know precise size of it.

I would expect this to work:

message, err := ioutil.ReadAll(conn)

But server is not sending EOF, so this statement just hangs.

I know its a JSON response, so I could read data until the last }, but that seems not the best way how it could be done.

What is the best practice to read full response?


update:

after some while I found out that it's possible this way:

var m map[string]interface{}
d := json.NewDecoder(conn)
d.Decode(&m)

for key, value := range m {
    fmt.Print(key)
    fmt.Print(" : ")
    fmt.Print(value)
    fmt.Print("
")
    switch vv := value.(type) {
    case map[string]interface{}:
        for k, v := range vv {
            fmt.Print(k)
            fmt.Print(" : ")
            fmt.Print(v)
            fmt.Print("
")
        }
    }
}

展开全部

  • 写回答

2条回答 默认 最新

  • douxin1884 2018-06-20 16:53
    关注

    Use a json.Decoder. Here's how to read multiple messages:

     d := json.NewDecoder(conn)
     for {
         var m message // <-- use whatever type is appropriate for your app
         err := d.Decode(&m)
         if err == io.EOF {
             break
         } else if err != nil {
             // handle error
         }
         // do something with m
    }
    

    Remove the loop if you expect exactly one message.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing
  • ¥15 手机/平板的浏览器里如何实现类似荧光笔的效果
  • ¥15 盘古气象大模型调用(python)
  • ¥15 传人记程序做的plc 485从机程序该如何写
  • ¥15 已知手指抓握过程中掌指关节、手指各关节和指尖每一帧的坐标,用贝塞尔曲线可以拟合手指抓握的运动轨迹吗?