main.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Solution to part 6 of the Whispering Gophers code lab.
  2. //
  3. // This program is functionally equivalent to part 5,
  4. // but the reading from standard input and writing to the
  5. // network connection are done by separate goroutines.
  6. //
  7. package main
  8. import (
  9. "bufio"
  10. "encoding/json"
  11. "flag"
  12. "fmt"
  13. "log"
  14. "net"
  15. "os"
  16. "code.google.com/p/whispering-gophers/util"
  17. )
  18. var (
  19. peerAddr = flag.String("peer", "", "peer host:port")
  20. self string
  21. )
  22. type Message struct {
  23. Addr string
  24. Body string
  25. }
  26. func main() {
  27. flag.Parse()
  28. l, err := util.Listen()
  29. if err != nil {
  30. log.Fatal(err)
  31. }
  32. self = l.Addr().String()
  33. log.Println("Listening on", self)
  34. go dial(*peerAddr)
  35. go readInput()
  36. for {
  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. defer c.Close()
  46. d := json.NewDecoder(c)
  47. for {
  48. var m Message
  49. err := d.Decode(&m)
  50. if err != nil {
  51. log.Println(err)
  52. return
  53. }
  54. fmt.Printf("%#v\n", m)
  55. }
  56. }
  57. // TODO: Make a new channel of Messages.
  58. var messages = make(chan Message)
  59. func readInput() {
  60. s := bufio.NewScanner(os.Stdin)
  61. for s.Scan() {
  62. m := Message{
  63. Addr: self,
  64. Body: s.Text(),
  65. }
  66. // TODO: Send the message to the channel of messages.
  67. messages <- m
  68. }
  69. if err := s.Err(); err != nil {
  70. log.Fatal(err)
  71. }
  72. }
  73. func dial(addr string) {
  74. c, err := net.Dial("tcp", addr)
  75. if err != nil {
  76. log.Println(addr, err)
  77. return
  78. }
  79. defer c.Close()
  80. e := json.NewEncoder(c)
  81. /* TODO: Receive messages from the channel using range, storing them in the variable m. */
  82. for m := range messages {
  83. err := e.Encode(m)
  84. if err != nil {
  85. log.Println(addr, err)
  86. return
  87. }
  88. }
  89. }