2016-04-29 164 views
2

我正在嘗試net.Pipe()。我認爲編寫"haha"字符串,然後閱讀它可能是一個很好的實驗。我該如何正確編寫'Read`和`Write` net.Pipe()`

這是我的第一個版本。在Write

func TestNetPipe(t *testing.T) { 
    out1 := make([]byte, 10) 
    c1, c2 := net.Pipe() 
    c1.Write([]byte("haha")) 
    c2.Read(out1) 
} 

它阻止我試圖用一個夠程

func TestNetPipe(t *testing.T) { 
    out1 := make([]byte, 10) 
    c1, c2 := net.Pipe() 
    go func() { 
     c1.Write([]byte("haha")) 
    }() 
    fmt.Printf("%v\n", out1) 
    c2.Read(out1) 
    fmt.Printf("%v\n", out1) 
} 

它的工作原理。但我覺得不能保證Read會讀取整個"haha"字符串。它可能只能讀取"hah"部分。

我不知道是否有更好的方法來從包io/ioutil演示net.Pipe()

回答

1

使用ReadAll函數的用法。

作爲ReadAll功能塊,直到EOF下面的代碼不需要goroutines同步。 close方法的調用會導致流上的EOF。

package main 

import (
    "fmt" 
    "io/ioutil" 
    "log" 
    "net" 
) 

func main() { 
    r, w := net.Pipe() 
    go func() { 
     w.Write([]byte("haha")) 
     w.Close() 
    }() 
    b, err := ioutil.ReadAll(r) 
    if err != nil { 
     log.Fatalf(err.Error()) 
    } 
    fmt.Println(string(b)) 
} 

Playground