websocket 增加多分组 fork https://github.com/olahol/melody
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package melody
  2. import (
  3. "sync"
  4. )
  5. type hub struct {
  6. sessions map[*Session]bool
  7. broadcast chan *envelope
  8. register chan *Session
  9. unregister chan *Session
  10. exit chan *envelope
  11. open bool
  12. rwmutex *sync.RWMutex
  13. }
  14. func newHub() *hub {
  15. return &hub{
  16. sessions: make(map[*Session]bool),
  17. broadcast: make(chan *envelope),
  18. register: make(chan *Session),
  19. unregister: make(chan *Session),
  20. exit: make(chan *envelope),
  21. open: true,
  22. rwmutex: &sync.RWMutex{},
  23. }
  24. }
  25. func (h *hub) run() {
  26. loop:
  27. for {
  28. select {
  29. case s := <-h.register:
  30. h.rwmutex.Lock()
  31. h.sessions[s] = true
  32. h.rwmutex.Unlock()
  33. case s := <-h.unregister:
  34. if _, ok := h.sessions[s]; ok {
  35. h.rwmutex.Lock()
  36. delete(h.sessions, s)
  37. h.rwmutex.Unlock()
  38. }
  39. case m := <-h.broadcast:
  40. h.rwmutex.RLock()
  41. for s := range h.sessions {
  42. if m.filter != nil {
  43. if m.filter(s) {
  44. s.writeMessage(m)
  45. }
  46. } else {
  47. s.writeMessage(m)
  48. }
  49. }
  50. h.rwmutex.RUnlock()
  51. case m := <-h.exit:
  52. h.rwmutex.Lock()
  53. for s := range h.sessions {
  54. s.writeMessage(m)
  55. delete(h.sessions, s)
  56. s.Close()
  57. }
  58. h.open = false
  59. h.rwmutex.Unlock()
  60. break loop
  61. }
  62. }
  63. }
  64. func (h *hub) closed() bool {
  65. h.rwmutex.RLock()
  66. defer h.rwmutex.RUnlock()
  67. return !h.open
  68. }
  69. func (h *hub) len() int {
  70. h.rwmutex.RLock()
  71. defer h.rwmutex.RUnlock()
  72. return len(h.sessions)
  73. }