part2.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 code.google.com/p/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. "flag"
  21. "log"
  22. "os"
  23. "net"
  24. "encoding/json"
  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. // TODO: Parse the flags.
  32. flag.Parse()
  33. // TODO: Open a new connection using the value of the "dial" flag.
  34. c, err := net.Dial("tcp", *dialAddr)
  35. // TODO: Don't forget to check the error.
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. s := bufio.NewScanner(os.Stdin)
  40. // TODO: Create a json.Encoder writing into the connection you created before.
  41. e := json.NewEncoder(c)
  42. for s.Scan() {
  43. m := Message{Body: s.Text()}
  44. err := e.Encode(m)
  45. if err != nil {
  46. log.Fatal(err)
  47. }
  48. }
  49. if err := s.Err(); err != nil {
  50. log.Fatal(err)
  51. }
  52. }