hub.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2013 The Gorilla WebSocket Authors. 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. if _, ok := h.connections[c]; ok {
  30. delete(h.connections, c)
  31. close(c.send)
  32. }
  33. case m := <-h.broadcast:
  34. for c := range h.connections {
  35. select {
  36. case c.send <- m:
  37. default:
  38. close(c.send)
  39. delete(h.connections, c)
  40. }
  41. }
  42. }
  43. }
  44. }