main.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "github.com/campoy/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. func readInput() {
  59. s := bufio.NewScanner(os.Stdin)
  60. for s.Scan() {
  61. m := Message{
  62. Addr: self,
  63. Body: s.Text(),
  64. }
  65. // TODO: Send the message to the channel of messages.
  66. }
  67. if err := s.Err(); err != nil {
  68. log.Fatal(err)
  69. }
  70. }
  71. func dial(addr string) {
  72. c, err := net.Dial("tcp", addr)
  73. if err != nil {
  74. log.Println(addr, err)
  75. return
  76. }
  77. defer c.Close()
  78. e := json.NewEncoder(c)
  79. for /* TODO: Receive messages from the channel using range, storing them in the variable m. */ {
  80. err := e.Encode(m)
  81. if err != nil {
  82. log.Println(addr, err)
  83. return
  84. }
  85. }
  86. }