package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"time"
)
func readData(bfRd io.Reader, dataChan chan []byte, endChan chan error) {
buf := make([]byte, 100)
for {
n, err := bfRd.Read(buf)
if err != nil {
endChan <- err
return
}
fmt.Printf("read data %s size \n", strconv.Itoa(n))
dataChan <- buf
}
}
func main() {
file, err := os.Open("client.go")
if err != nil {
log.Fatalln(err)
}
var data []byte
bfRd := bufio.NewReader(file)
var dataChan = make(chan []byte)
var endChan = make(chan error)
go readData(bfRd, dataChan, endChan)
for {
select {
case <-endChan:
fmt.Println(<-endChan)
break
case <-dataChan:
data = append(data, <-dataChan...)
case <-time.After(time.Second):
fmt.Println("timeout")
break
default:
fmt.Println("channel cannot use")
}
}
fmt.Println(string(data))
}
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)