main.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Solution to part 2 of the Whispering Gophers code lab.
  2. //
  3. // This program extends part 1.
  4. //
  5. // It makes a connection the host and port specified by the -dial flag, reads
  6. // lines from standard input and writes JSON-encoded messages to the network
  7. // connection.
  8. //
  9. // You can test this program by installing and running the dump program:
  10. // $ go get github.com/campoy/whispering-gophers/util/dump
  11. // $ dump -listen=localhost:8000
  12. // And in another terminal session, run this program:
  13. // $ part2 -dial=localhost:8000
  14. // Lines typed in the second terminal should appear as JSON objects in the
  15. // first terminal.
  16. //
  17. package main
  18. import (
  19. "bufio"
  20. "encoding/json"
  21. "flag"
  22. "log"
  23. "net"
  24. "os"
  25. )
  26. var dialAddr = flag.String("dial", "localhost:8000", "host:port to dial")
  27. type Message struct {
  28. Body string
  29. }
  30. func main() {
  31. flag.Parse()
  32. c, err := net.Dial("tcp4", *dialAddr)
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36. s := bufio.NewScanner(os.Stdin)
  37. e := json.NewEncoder(c)
  38. for s.Scan() {
  39. m := Message{Body: s.Text()}
  40. err := e.Encode(m)
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. }
  45. if err := s.Err(); err != nil {
  46. log.Fatal(err)
  47. }
  48. }