练习 8.4: 修改reverb2服务器,在每一个连接中使用sync.WaitGroup来计数活跃的echo goroutine。当计数减为零时,关闭TCP连接的写入,像练习8.3中一样。验证一下你的修改版netcat3客户端会一直等待所有的并发“喊叫”完成,即使是在标准输入流已经关闭的情况下。
重点:等待所有的goroutine执行完成后再关闭TCP连接
package main import ( "bufio" "fmt" "log" "net" "strings" "time" "sync" ) func main() { listener, err := net.Listen("tcp", ":8040") if err != nil { log.Fatal(err) } for { conn, err := listener.Accept() if err != nil { log.Print(err) // e.g., connection aborted continue } go handleConn(conn) //新建goroutines处理连接 } } func handleConn(c net.Conn) { input := bufio.NewScanner(c) var wg sync.WaitGroup //var ch =make(chan struct{}) for input.Scan() { wg.Add(1) go func(c net.Conn, shout string, delay time.Duration) { defer wg.Done() fmt.Fprintln(c, " ", strings.ToUpper(shout)) time.Sleep(delay) fmt.Fprintln(c, " ", shout) time.Sleep(delay) fmt.Fprintln(c, " ", strings.ToLower(shout)) //ch<-struct{}{} }(c, input.Text(), 1*time.Second) } wg.Wait() //cw := c.(*net.TCPConn) //cw.CloseWrite() c.Close() }