part3.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. "io"
  21. "log"
  22. "net"
  23. )
  24. var listenAddr = flag.String("listen", "localhost:8000", "host:port to listen on")
  25. type Message struct {
  26. Body string
  27. }
  28. func main() {
  29. flag.Parse()
  30. // TODO: Create a net.Listener listening from the address in the "listen" flag.
  31. l, err := net.Listen("tcp", *listenAddr)
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. for {
  36. // TODO: Accept a new connection from the listener.
  37. c, err := l.Accept()
  38. if err != nil {
  39. log.Fatal(err)
  40. }
  41. go serve(c)
  42. }
  43. }
  44. func serve(c net.Conn) {
  45. // TODO: Use defer to Close the connection when this function returns.
  46. defer c.Close()
  47. // TODO: Create a new json.Decoder reading from the connection.
  48. e := json.NewDecoder(c)
  49. for {
  50. // TODO: Create an empty message.
  51. m := Message{}
  52. // TODO: Decode a new message into the variable you just created.
  53. err := e.Decode(&m)
  54. switch err {
  55. case nil:
  56. // TODO: Print the message to the standard output.
  57. fmt.Printf("%+v\n", m)
  58. case io.EOF:
  59. log.Println("End of input")
  60. return
  61. default:
  62. log.Fatal(err)
  63. }
  64. }
  65. }