hub.go 1.2 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 mainHub = 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 (hub *hub) run() {
  24. for {
  25. select {
  26. case conn := <-hub.register:
  27. hub.connections[conn] = true
  28. case conn := <-hub.unregister:
  29. if _, ok := hub.connections[conn]; ok {
  30. delete(hub.connections, conn)
  31. close(conn.send)
  32. }
  33. case message := <-hub.broadcast:
  34. for conn := range hub.connections {
  35. select {
  36. case conn.send <- message:
  37. default:
  38. close(conn.send)
  39. delete(hub.connections, conn)
  40. }
  41. }
  42. }
  43. }
  44. }