go - Read whole data with Golang net.Conn.Read -
go - Read whole data with Golang net.Conn.Read -
so i'm building network app in go , i've seen conn.read
reads limited byte array, had created make([]byte, 2048)
, problem don't know exact length of content, much or not enough. question how can read exact amount of data. think have utilize bufio
, i'm not sure.
it highly depends on you're trying do, , kind of info you're expecting, illustration if want read until eof utilize this:
func main() { conn, err := net.dial("tcp", "google.com:80") if err != nil { fmt.println("dial error:", err) homecoming } 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 little tmo buffer demonstrating { 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: completeness sake , @fabriziom's great suggestion, skipped mind:
func main() { conn, err := net.dial("tcp", "google.com:80") if err != nil { fmt.println("dial error:", err) homecoming } 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()) }
go
Comments
Post a Comment