Exercise 8.1: Modify Clock2 to support incoming parameters as port numbers, and then write a clockwall program that can communicate with multiple clock servers simultaneously, read time from multiple servers, and display the results of all services at once in a single table. Similar to the clock wall you see in some offices. If you have a geographically distributed server that can be used to run on different machines, or run multiple instances on the same machine, listen to different ports and pretend to be in a different time zone. Like this:
$ TZ=US/Eastern ./clock2 -port 8010 &$ TZ=Asia/Tokyo ./clock2 -port 8020 &$ TZ=Europe/London ./clock2 -port 8030 &$ clockwall NewYork=localhost:8010 Tokyo=localhost:8020 London=localhost:8030
Clock2.go
Package Mainimport ( "flag" "IO" " log" "NET" "Time")//support incoming parameter as port number var port = flag. String ("Port", "8000", "Please enter Port") Func main () { flag. Parse () listener, err: = Net. Listen ("tcp", "localhost:" +*port) 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)//New Goroutines processing connection } }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) } }
Clockwall.go
NETCAT1 is a read-only TCP client.package mainimport ( "io" "log" "NET" " OS" "Strings" " Time ") Func main () { for _, V: = Range os. Args[1:] { KeyValue: = Strings. Split (V, "=") go conntcp (keyvalue[1]) } for {time . Sleep (1 * time. Second) } }func conntcp (URI string) { conn, err: = Net. Dial ("TCP", URI) if err! = Nil { log. Fatal (Err) } defer conn. Close () mustcopy (OS. STDOUT, conn)}func mustcopy (DST io. Writer, src io. Reader) { If _, err: = Io. Copy (DST, SRC); Err! = Nil { log. Fatal (Err) } }
Daily Go Language Bible-Example: concurrent clock service exercises