hub.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2013 Gary Burd. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. // hub maintains the set of active connections and broadcasts messages to the
  6. // connections.
  7. type hub struct {
  8. // Registered connections.
  9. connections map[*connection]bool
  10. // Inbound messages from the connections.
  11. broadcast chan []byte
  12. // Register requests from the connections.
  13. register chan *connection
  14. // Unregister requests from connections.
  15. unregister chan *connection
  16. }
  17. var h = hub{
  18. broadcast: make(chan []byte),
  19. register: make(chan *connection),
  20. unregister: make(chan *connection),
  21. connections: make(map[*connection]bool),
  22. }
  23. func (h *hub) run() {
  24. for {
  25. select {
  26. case c := <-h.register:
  27. h.connections[c] = true
  28. case c := <-h.unregister:
  29. delete(h.connections, c)
  30. close(c.send)
  31. case m := <-h.broadcast:
  32. for c := range h.connections {
  33. select {
  34. case c.send <- m:
  35. default:
  36. close(c.send)
  37. delete(h.connections, c)
  38. }
  39. }
  40. }
  41. }
  42. }