hub.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright 2013 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package web
  14. type hub struct {
  15. // status
  16. open bool
  17. // Registered connections.
  18. connections map[*connection]bool
  19. // Inbound messages from the connections.
  20. broadcast chan string
  21. // Register requests from the connections.
  22. register chan *connection
  23. // Unregister requests from connections.
  24. unregister chan *connection
  25. }
  26. var h = hub{
  27. open: false,
  28. broadcast: make(chan string),
  29. register: make(chan *connection),
  30. unregister: make(chan *connection),
  31. connections: make(map[*connection]bool),
  32. }
  33. func Hub() *hub {
  34. return &h
  35. }
  36. func HubOpen() bool {
  37. return h.open
  38. }
  39. func (h *hub) run() {
  40. h.open = true
  41. for {
  42. select {
  43. case c := <-h.register:
  44. h.connections[c] = true
  45. case c := <-h.unregister:
  46. delete(h.connections, c)
  47. close(c.send)
  48. case m := <-h.broadcast:
  49. for c := range h.connections {
  50. select {
  51. case c.send <- m:
  52. default:
  53. delete(h.connections, c)
  54. close(c.send)
  55. go c.ws.Close()
  56. }
  57. }
  58. }
  59. }
  60. }
  61. func (h *hub) Send(msg string) {
  62. h.broadcast <- msg
  63. }