main.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Solution to part 3 of the Whispering Gophers code lab.
  2. //
  3. // This program listens on the host and port specified by the -listen flag.
  4. // For each incoming connection, it launches a goroutine that reads and decodes
  5. // JSON-encoded messages from the connection and prints them to standard
  6. // output.
  7. //
  8. // You can test this program by running it in one terminal:
  9. // $ part3 -listen=localhost:8000
  10. // And running part2 in another terminal:
  11. // $ part2 -dial=localhost:8000
  12. // Lines typed in the second terminal should appear as JSON objects in the
  13. // first terminal.
  14. //
  15. package main
  16. import (
  17. "encoding/json"
  18. "flag"
  19. "fmt"
  20. "log"
  21. "net"
  22. )
  23. var listenAddr = flag.String("listen", "localhost:8000", "host:port to listen on")
  24. type Message struct {
  25. Body string
  26. }
  27. func main() {
  28. flag.Parse()
  29. // TODO: Create a net.Listener listening from the address in the "listen" flag.
  30. for {
  31. // TODO: Accept a new connection from the listener.
  32. go serve(c)
  33. }
  34. }
  35. func serve(c net.Conn) {
  36. // TODO: Use defer to Close the connection when this function returns.
  37. // TODO: Create a new json.Decoder reading from the connection.
  38. for {
  39. // TODO: Create an empty message.
  40. // TODO: Decode a new message into the variable you just created.
  41. // TODO: Print the message to the standard output.
  42. }
  43. }