Last active
April 23, 2020 21:41
-
-
Save santakdalai90/6a2219eb72a8e8ce3a9eeac9ba7078fc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Clockserver publishes time on a given port as command line argument | |
// Usage: TZ=US/Eastern ./exercise8_1 8000 & | |
package main | |
import ( | |
"io" | |
"log" | |
"net" | |
"time" | |
"os" | |
"fmt" | |
) | |
func main() { | |
port := os.Args[1] | |
listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%s", port)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
log.Print(err) | |
continue | |
} | |
go handleConn(conn) | |
} | |
} | |
func handleConn(c net.Conn) { | |
defer c.Close() | |
for { | |
_, err := io.WriteString(c, time.Now().Format("03:04:05PM\n")) | |
if err != nil { | |
return | |
} | |
time.Sleep(1 * time.Second) | |
} | |
} |
This file contains hidden or 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
// Clockwall shows multiple times concurrently | |
// usage: ./clockwall NewYork=localhost:8000 Tokyo=localhost:8010 | |
package main | |
import ( | |
"fmt" | |
"bufio" | |
"net" | |
"os" | |
"log" | |
"strings" | |
"sync" | |
) | |
func displayClock(timeZone, serverAddr, serverPort string, wg *sync.WaitGroup) { | |
defer wg.Done() | |
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", serverAddr, serverPort)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer conn.Close() | |
s := bufio.NewScanner(conn) | |
for s.Scan() { | |
fmt.Fprintf(os.Stdout, "%-15s: %s\n", timeZone, s.Text()) | |
} | |
} | |
func main() { | |
// read params | |
var wg sync.WaitGroup | |
for _, arg := range os.Args[1:] { | |
pArr := strings.Split(arg,"=") | |
timeZone := pArr[0] | |
serverAddr := strings.Split(pArr[1],":")[0] | |
serverPort := strings.Split(pArr[1],":")[1] | |
wg.Add(1) | |
go displayClock(timeZone, serverAddr, serverPort, &wg) | |
} | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment