標籤:one mes 語句 sleep sele 基於 class fat log
練習 8.8: 使用select來改造8.3節中的echo伺服器,為其增加逾時,這樣伺服器可以在用戶端10秒中沒有任何喊話時自動中斷連線。
reverb3.go
package mainimport ( "bufio" "fmt" "log" "net" "strings" "sync" "time")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處理串連 }}/*1.啟動一個goroutine,for死迴圈讓他不能斷掉select語句case判斷兩個channel一個是10秒後斷掉串連另一個是接收標準輸入後發送過來的channel,接收到值後,啟動goroutinue輸出2.for迴圈接收標準輸入,接收到後發送給message的channel*/func handleConn(c net.Conn) { input := bufio.NewScanner(c) var wg sync.WaitGroup var message = make(chan string) wg.Add(1) go func() { defer wg.Done() for { select { case <-time.After(10 * time.Second): c.Close() case mes := <-message: wg.Add(1) go func(c net.Conn, shout string, delay time.Duration) { defer wg.Done() fmt.Fprintln(c, "\t", strings.ToUpper(shout)) time.Sleep(delay) fmt.Fprintln(c, "\t", shout) time.Sleep(delay) fmt.Fprintln(c, "\t", strings.ToLower(shout)) //ch<-struct{}{} }(c, mes, 1*time.Second) } } }() for input.Scan() { text := input.Text() message <- text } wg.Wait() //cw := c.(*net.TCPConn) //cw.CloseWrite() c.Close()}
[日常] Go語言聖經-基於select的多工習題