Read whole data with Golang net.Conn.Read

前端 未结 3 797
时光取名叫无心
时光取名叫无心 2020-12-25 12:27

So I\'m building a network app in Go and I\'ve seen that Conn.Read reads into a limited byte array, which I had created with make([]byte, 2048) and

相关标签:
3条回答
  • 2020-12-25 13:06

    You can read data something like this:

    // import net/textproto
    import ("net/textproto", ...)
    
    ....
    
    reader := bufio.NewReader(Conn)
    tp := textproto.NewReader(reader)
    
    defer Conn.Close()
    
    for {
        // read one line (ended with \n or \r\n)
        line, _ := tp.ReadLine()
        // do something with data here, concat, handle and etc... 
    }
    ....
    
    0 讨论(0)
  • 2020-12-25 13:09

    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\r\n\r\n")
    
        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\r\n\r\n")
        var buf bytes.Buffer
        io.Copy(&buf, conn)
        fmt.Println("total size:", buf.Len())
    }
    
    0 讨论(0)
  • 2020-12-25 13:11

    You can use the ioutil.ReadAll function:

    import (
        "fmt"
        "io/ioutil"
        "net"
    )
    
    func whois(domain, server string) ([]byte, error) {
        conn, err := net.Dial("tcp", server+":43")
        if err != nil {
            return nil, err
        }
        defer conn.Close()
    
        fmt.Fprintf(conn, "%s\r\n", domain)
        return ioutil.ReadAll(conn)
    }
    
    0 讨论(0)
提交回复
热议问题