main.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // Skeleton to part 8 of the Whispering Gophers code lab.
  2. //
  3. // This program extends part 7.
  4. //
  5. // It connects to the peer specified by -peer.
  6. // It accepts connections from peers and receives messages from them.
  7. // When it sees a peer with an address it hasn't seen before, it opens a
  8. // connection to that peer.
  9. //
  10. package main
  11. import (
  12. "bufio"
  13. "encoding/json"
  14. "flag"
  15. "fmt"
  16. "log"
  17. "net"
  18. "os"
  19. "sync"
  20. "github.com/campoy/whispering-gophers/util"
  21. )
  22. var (
  23. peerAddr = flag.String("peer", "", "peer host:port")
  24. self string
  25. )
  26. type Message struct {
  27. Addr string
  28. Body string
  29. }
  30. func main() {
  31. flag.Parse()
  32. l, err := util.Listen()
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36. self = l.Addr().String()
  37. log.Println("Listening on", self)
  38. go dial(*peerAddr)
  39. go readInput()
  40. for {
  41. c, err := l.Accept()
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. go serve(c)
  46. }
  47. }
  48. // TODO: create a global shared Peers instance
  49. type Peers struct {
  50. m map[string]chan<- Message
  51. mu sync.RWMutex
  52. }
  53. // Add creates and returns a new channel for the given peer address.
  54. // If an address already exists in the registry, it returns nil.
  55. func (p *Peers) Add(addr string) <-chan Message {
  56. p.mu.Lock()
  57. defer p.mu.Unlock()
  58. if _, ok := p.m[addr]; ok {
  59. return nil
  60. }
  61. ch := make(chan Message)
  62. p.m[addr] = ch
  63. return ch
  64. }
  65. // Remove deletes the specified peer from the registry.
  66. func (p *Peers) Remove(addr string) {
  67. p.mu.Lock()
  68. defer p.mu.Unlock()
  69. delete(p.m, addr)
  70. }
  71. // List returns a slice of all active peer channels.
  72. func (p *Peers) List() []chan<- Message {
  73. p.mu.RLock()
  74. defer p.mu.RUnlock()
  75. l := make([]chan<- Message, 0, len(p.m))
  76. for _, ch := range p.m {
  77. l = append(l, ch)
  78. }
  79. return l
  80. }
  81. func broadcast(m Message) {
  82. for /* TODO: Range over the list of peers */ {
  83. // TODO: Send a message to the channel, but don't block.
  84. // Hint: Select is your friend.
  85. }
  86. }
  87. func serve(c net.Conn) {
  88. defer c.Close()
  89. d := json.NewDecoder(c)
  90. for {
  91. var m Message
  92. err := d.Decode(&m)
  93. if err != nil {
  94. log.Println(err)
  95. return
  96. }
  97. // TODO: Launch dial in a new goroutine, to connect to the address in the message's Addr field.
  98. fmt.Printf("%#v\n", m)
  99. }
  100. }
  101. func readInput() {
  102. s := bufio.NewScanner(os.Stdin)
  103. for s.Scan() {
  104. m := Message{
  105. Addr: self,
  106. Body: s.Text(),
  107. }
  108. broadcast(m)
  109. }
  110. if err := s.Err(); err != nil {
  111. log.Fatal(err)
  112. }
  113. }
  114. func dial(addr string) {
  115. // TODO: If dialing self, return.
  116. // TODO: Add the address to the peers map.
  117. // TODO: If you get a nil channel the peer is already connected, return.
  118. // TODO: Remove the address from peers map when this function returns
  119. // (use defer).
  120. c, err := net.Dial("tcp", addr)
  121. if err != nil {
  122. log.Println(addr, err)
  123. return
  124. }
  125. defer c.Close()
  126. e := json.NewEncoder(c)
  127. for m := range ch {
  128. err := e.Encode(m)
  129. if err != nil {
  130. log.Println(addr, err)
  131. return
  132. }
  133. }
  134. }