ch8/ch8-07 #178
ch8/ch8-07
#178
Replies: 3 comments 2 replies
-
func main() {
port := flag.String("port", "8080", "defalt 8080")
flag.Parse()
listener, err := net.Listen("tcp", "127.0.0.1:"+*port)
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go handle(conn)
}
}
func idle(c net.Conn, reset <-chan struct{}) {
ticker := time.NewTicker(1 * time.Second)
for i := 0; i < 10; i++ {
select {
case <-ticker.C: //没收到重置就计时
case <-reset: //收到重置就归0
i = 0
}
}
ticker.Stop()
c.(*net.TCPConn).CloseRead() //计时完毕关闭写方向,使得Scan退出阻塞
}
func handle(c net.Conn) {
defer func() {
c.Close()
fmt.Println(c.RemoteAddr(), "has closed")
}()
reset := make(chan struct{})
go idle(c, reset)
scanner := bufio.NewScanner(c)
for scanner.Scan() {
reset <- struct{}{} //收到消息就重置
echo(c, scanner.Text(), 1*time.Second)
}
}
func echo(c net.Conn, s string, delay time.Duration) {
fmt.Fprintln(c, "\t", strings.ToUpper(s))
time.Sleep(delay)
fmt.Fprintln(c, "\t", s)
time.Sleep(delay)
fmt.Fprintln(c, "\t", strings.ToLower(s))
} |
Beta Was this translation helpful? Give feedback.
2 replies
-
不知所云 |
Beta Was this translation helpful? Give feedback.
0 replies
-
取名为select和multiplex还挺形象的,很像epoll那套思路,把每个chan理解为fd,然后select就像epoll_wait |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
ch8/ch8-07
中文版
https://gopl-zh.github.io/ch8/ch8-07.html
Beta Was this translation helpful? Give feedback.
All reactions