doumaogui5937 2014-06-21 08:06 采纳率: 100%
浏览 3260
已采纳

用Golang net.Conn.Read读取整个数据出错

我在Go中构建了一个网络应用程序,我看到Conn.Read读取一个有限的字节数组,这个数组是我用make([]字节,2048)创建的,现在的问题是我不知道内容的确切长度,所以它可能太多或者不够。

我的问题是,我如何才能读到确切的数据量?我想我得用bufio,但我不确定。能不能行得通。

  • 写回答

3条回答 默认 最新

  • doubingjiu3199 2014-06-21 15:45
    关注

    It highly depends on what you're trying to do, and what kind of data you're expecting, for example if you just want to read until the EOF you could use something like this:

    func main() {
        conn, err := net.Dial("tcp", "google.com:80")
        if err != nil {
            fmt.Println("dial error:", err)
            return
        }
        defer conn.Close()
        fmt.Fprintf(conn, "GET / HTTP/1.0
    
    ")
    
        buf := make([]byte, 0, 4096) // big buffer
        tmp := make([]byte, 256)     // using small tmo buffer for demonstrating
        for {
            n, err := conn.Read(tmp)
            if err != nil {
                if err != io.EOF {
                    fmt.Println("read error:", err)
                }
                break
            }
            //fmt.Println("got", n, "bytes.")
            buf = append(buf, tmp[:n]...)
    
        }
        fmt.Println("total size:", len(buf))
        //fmt.Println(string(buf))
    }
    

    //edit: for completeness sake and @fabrizioM's great suggestion, which completely skipped my mind:

    func main() {
        conn, err := net.Dial("tcp", "google.com:80")
        if err != nil {
            fmt.Println("dial error:", err)
            return
        }
        defer conn.Close()
        fmt.Fprintf(conn, "GET / HTTP/1.0
    
    ")
        var buf bytes.Buffer
        io.Copy(&buf, conn)
        fmt.Println("total size:", buf.Len())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题