Skip to content

Instantly share code, notes, and snippets.

@gerep
Last active Nov 18, 2017
Embed
What would you like to do?
// Execution example: TZ=US/Eastern ./clock2 --port 8000
package main
import (
"flag"
"io"
"log"
"net"
"os"
"time"
)
func main() {
port := flag.String("port", "8000", "port")
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)
continue
}
// Runs the handler as a goroutine to allow simultaneous clients.
go handleConn(conn, os.Getenv("TZ"))
}
}
func handleConn(c net.Conn, tz string) {
defer c.Close()
// Set the time that will be used.
loc, err := time.LoadLocation(tz)
if err != nil {
log.Fatal(err)
}
for {
// Writes to the connection the time based on the timezone, with In(loc).
_, err := io.WriteString(c, time.Now().In(loc).Format("15:04:05\n"))
if err != nil {
return
}
time.Sleep(1 * time.Second)
}
}
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"time"
)
// Zone will store each timezone informed as argument to the binary.
type zone struct {
name, server string
}
func main() {
zones := []zone{}
for _, e := range os.Args[1:] {
v := strings.Split(e, "=")
zones = append(zones, zone{v[0], v[1]})
}
// For each zone, start a net.Dial to receive data from the server.
for _, v := range zones {
conn, err := net.Dial("tcp", v.server)
defer conn.Close()
if err != nil {
log.Fatal(err)
}
// Start the copy process as a goroutine to show all available zones.
go mustCopy(os.Stdout, conn, v.name)
}
// Force main to wait.
time.Sleep(5 * time.Second)
}
// Reads the information being sent in the connection via the src parameter
// and print to dst the name and hour returned by the server: somewhere: 00:00:00
func mustCopy(dst io.Writer, src io.Reader, n string) {
s := bufio.NewScanner(src)
for s.Scan() {
fmt.Fprintf(dst, "%s: %s\n", n, s.Text())
}
if s.Err() != nil {
fmt.Printf("error reading from %s: %v", n, s.Err())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment