hub.go 977 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package internal
  2. // Hub maintains the set of active clients and broadcasts messages to the
  3. // clients.
  4. type Hub struct {
  5. // Registered clients.
  6. clients map[*Client]bool
  7. // Inbound messages from the clients.
  8. broadcast chan []byte
  9. // Register requests from the clients.
  10. register chan *Client
  11. // Unregister requests from clients.
  12. unregister chan *Client
  13. }
  14. func NewHub() *Hub {
  15. return &Hub{
  16. broadcast: make(chan []byte),
  17. register: make(chan *Client),
  18. unregister: make(chan *Client),
  19. clients: make(map[*Client]bool),
  20. }
  21. }
  22. func (h *Hub) Run() {
  23. for {
  24. select {
  25. case client := <-h.register:
  26. h.clients[client] = true
  27. case client := <-h.unregister:
  28. if _, ok := h.clients[client]; ok {
  29. delete(h.clients, client)
  30. close(client.send)
  31. }
  32. case message := <-h.broadcast:
  33. for client := range h.clients {
  34. select {
  35. case client.send <- message:
  36. default:
  37. close(client.send)
  38. delete(h.clients, client)
  39. }
  40. }
  41. }
  42. }
  43. }