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.

55 lines
993 B

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. type hub struct {
  3. sessions map[*Session]bool
  4. broadcast chan *envelope
  5. register chan *Session
  6. unregister chan *Session
  7. exit chan bool
  8. open bool
  9. }
  10. func newHub() *hub {
  11. return &hub{
  12. sessions: make(map[*Session]bool),
  13. broadcast: make(chan *envelope),
  14. register: make(chan *Session),
  15. unregister: make(chan *Session),
  16. exit: make(chan bool),
  17. open: true,
  18. }
  19. }
  20. func (h *hub) run() {
  21. loop:
  22. for {
  23. select {
  24. case s := <-h.register:
  25. h.sessions[s] = true
  26. case s := <-h.unregister:
  27. if _, ok := h.sessions[s]; ok {
  28. delete(h.sessions, s)
  29. s.conn.Close()
  30. close(s.output)
  31. }
  32. case m := <-h.broadcast:
  33. for s := range h.sessions {
  34. if m.filter != nil {
  35. if m.filter(s) {
  36. s.writeMessage(m)
  37. }
  38. } else {
  39. s.writeMessage(m)
  40. }
  41. }
  42. case <-h.exit:
  43. for s := range h.sessions {
  44. delete(h.sessions, s)
  45. s.conn.Close()
  46. close(s.output)
  47. }
  48. h.open = false
  49. break loop
  50. }
  51. }
  52. }