Last active
October 20, 2018 14:57
-
-
Save ibreathebsb/5efd7ebf5e0d5e1d571461c826560952 to your computer and use it in GitHub Desktop.
Exercise 8.8: Using a select statement, add a timeout to the echo server from Section 8.3 so that it disconnects any client that shouts nothing within 10 seconds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"net" | |
"time" | |
) | |
func main() { | |
l, err := net.Listen("tcp", ":8080") | |
if nil != err { | |
panic(err) | |
} | |
for { | |
con, err := l.Accept() | |
if err != nil { | |
continue | |
} | |
go func(c net.Conn) { | |
defer c.Close() | |
ch := make(chan string) | |
go func(ch chan<- string) { | |
s := bufio.NewScanner(c) | |
for s.Scan() { | |
ch <- s.Text() | |
} | |
}(ch) | |
for { | |
select { | |
case <-time.After(10 * time.Second): | |
fmt.Println("time out") | |
return | |
case text := <-ch: | |
io.WriteString(c, text) | |
} | |
} | |
}(con) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment