Skip to content

Instantly share code, notes, and snippets.

@ibreathebsb
Last active October 20, 2018 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibreathebsb/5efd7ebf5e0d5e1d571461c826560952 to your computer and use it in GitHub Desktop.
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.
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