2 回答

TA貢獻1793條經驗 獲得超6個贊
你不能close多次調用一個通道,沒有理由調用copyfor 循環,因為它只能運行一次,而且你正在向錯誤的方向復制,寫入標準輸入并從標準輸出讀取。
簡單地詢問如何退出 2 個 goroutines 很簡單,但這不是您在這里需要做的唯一事情。由于io.Copy是阻塞,您不需要額外的同步來確定調用何時完成。這使您可以顯著簡化代碼,從而更容易推理。
func interact(c net.Conn) {
go func() {
// You want to close this outside the goroutine if you
// expect to send data back over a half-closed connection
defer c.Close()
// Optionally close stdout here if you need to signal the
// end of the stream in a pipeline.
defer os.Stdout.Close()
_, err := io.Copy(os.Stdout, c)
if err != nil {
//
}
}()
_, err := io.Copy(c, os.Stdin)
if err != nil {
//
}
}
另請注意,您可能無法跳出io.Copyfrom stdin,因此您不能指望函數interact返回。在函數體中手動執行io.Copy并檢查每個循環的半關閉連接可能是個好主意,這樣您就可以更快地退出并確保完全關閉net.Conn.

TA貢獻1876條經驗 獲得超5個贊
也可以是這樣的
func scanReader(quit chan int, r io.Reader) chan string {
line := make(chan string)
go func(quit chan int) {
defer close(line)
scan := bufio.NewScanner(r)
for scan.Scan() {
select {
case <- quit:
return
default:
s := scan.Text()
line <- s
}
}
}(quit)
return line
}
stdIn := scanReader(quit, os.Stdin)
conIn := scanReader(quit, c)
for {
select {
case <-quit:
return
case l <- stdIn:
_, e := fmt.Fprintf(c, l)
if e != nil {
quit <- 1
return
}
case l <- conIn:
fmt.Println(l)
}
}
- 2 回答
- 0 關注
- 151 瀏覽
添加回答
舉報