mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 14:42:01 +00:00
good good study, day day up!
This commit is contained in:
42
vendor/gopl.io/ch8/clock2/clock.go
generated
vendored
Normal file
42
vendor/gopl.io/ch8/clock2/clock.go
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 222.
|
||||
|
||||
// Clock is a TCP server that periodically writes the time.
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
func handleConn(c net.Conn) {
|
||||
defer c.Close()
|
||||
for {
|
||||
_, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
|
||||
if err != nil {
|
||||
return // e.g., client disconnected
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
listener, err := net.Listen("tcp", "localhost:8000")
|
||||
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) // handle connections concurrently
|
||||
}
|
||||
//!-
|
||||
}
|
Reference in New Issue
Block a user