Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect 8.1 -> clockwall.go #20

Open
unmarshall opened this issue Sep 9, 2019 · 0 comments
Open

Incorrect 8.1 -> clockwall.go #20

unmarshall opened this issue Sep 9, 2019 · 0 comments

Comments

@unmarshall
Copy link

Hello,
If you execute the program then it gives
./clockwall NewYork=localhost:8010 London=localhost:8020 NewYork done 2019/09/09 11:01:08 cannot read from NewYork : read tcp 127.0.0.1:60572->127.0.0.1:8010: use of closed network connection London done 2019/09/09 11:01:08 cannot read from London : read tcp 127.0.0.1:60573->127.0.0.1:8020: use of closed network connection 2019/09/09 11:01:09 write tcp 127.0.0.1:8010->127.0.0.1:60572: write: broken pipe 2019/09/09 11:01:09 write tcp 127.0.0.1:8020->127.0.0.1:60573: write: broken pipe [1] - 49198 exit 1 ./clock -port 8010 [2] + 49216 exit 1 ./clock -port 8020
You also have a sleep in the main loop to allow sufficient time for all goroutines to finish when actually they never finish as the time is printed every second.

I have attached changed code which will work.
`
package main

import (
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
)

type clock struct {
name, host string
}

func main() {
if len(os.Args) == 1 {
fmt.Fprintln(os.Stderr, "usage: clockwall NAME=HOST ...")
os.Exit(1)
}
clocks := createClocks(os.Args[1:])
var wg sync.WaitGroup
wg.Add(len(clocks))
for _, c := range clocks {
go startWatching(c, wg)
}
wg.Wait()
}

func (c *clock) watch(w io.Writer, r io.Reader) {
if _, err := io.Copy(w, r); err != nil {
log.Fatal(err)
}
}

func startWatching(c *clock, wg sync.WaitGroup) {
conn, err := net.Dial("tcp", c.host)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
defer wg.Done()
c.watch(os.Stdout, conn)
}

func createClocks(args []string) (clocks []*clock) {
clocks = make([]*clock, 0)
for _, pair := range args {
fields := strings.Split(pair, "=")
if len(fields) != 2 {
fmt.Fprintf(os.Stderr, "bad arg: %s\n", pair)
os.Exit(1)
}
clocks = append(clocks, &clock{fields[0], fields[1]})
}
return
}

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant