hub.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package web
  2. type hub struct {
  3. // status
  4. open bool
  5. // Registered connections.
  6. connections map[*connection]bool
  7. // Inbound messages from the connections.
  8. broadcast chan string
  9. // Register requests from the connections.
  10. register chan *connection
  11. // Unregister requests from connections.
  12. unregister chan *connection
  13. }
  14. var h = hub{
  15. open: false,
  16. broadcast: make(chan string),
  17. register: make(chan *connection),
  18. unregister: make(chan *connection),
  19. connections: make(map[*connection]bool),
  20. }
  21. func Hub() *hub {
  22. return &h
  23. }
  24. func HubOpen() bool {
  25. return h.open
  26. }
  27. func (h *hub) run() {
  28. h.open = true
  29. for {
  30. select {
  31. case c := <-h.register:
  32. h.connections[c] = true
  33. case c := <-h.unregister:
  34. delete(h.connections, c)
  35. close(c.send)
  36. case m := <-h.broadcast:
  37. for c := range h.connections {
  38. select {
  39. case c.send <- m:
  40. default:
  41. delete(h.connections, c)
  42. close(c.send)
  43. go c.ws.Close()
  44. }
  45. }
  46. }
  47. }
  48. }
  49. func (h *hub) Send(msg string) {
  50. h.broadcast <- msg
  51. }