Exercise 8.8: Use Select to transform the Echo Server in section 8.3 to increase the timeout so that the server can automatically disconnect when there is no shouting in the client for 10 seconds.
Reverb3.go
Package Mainimport ("Bufio" "FMT" "Log" "NET" "Strings" "Sync" "Time") Fu NC 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) The new Goroutines handles the connection}}/*1. Start a goroutine,for cycle so he can't break the SELECT statement case judgment two Channel One is 10 seconds after the disconnection of the connection another is to receive the standard input sent over the channel, After receiving the value, start the goroutinue output 2.for loop to receive the standard input, and receive the Channel*/func Handleconn (c net) that is sent to the message. 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 (Ten * 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 ()}
Daily Go Language Bible-a select-based approach to multiplexing exercises