Daily Go Language Bible-a select-based approach to multiplexing exercises

Source: Internet
Author: User

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: = &LT;-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.