hub.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. // hub maintains the set of active clients and broadcasts messages to the
  6. // clients.
  7. type Hub struct {
  8. // Registered clients.
  9. clients map[*Client]bool
  10. // Inbound messages from the clients.
  11. broadcast chan []byte
  12. // Register requests from the clients.
  13. register chan *Client
  14. // Unregister requests from clients.
  15. unregister chan *Client
  16. }
  17. func newHub() *Hub {
  18. return &Hub{
  19. broadcast: make(chan []byte),
  20. register: make(chan *Client),
  21. unregister: make(chan *Client),
  22. clients: make(map[*Client]bool),
  23. }
  24. }
  25. func (h *Hub) run() {
  26. for {
  27. select {
  28. case client := <-h.register:
  29. h.clients[client] = true
  30. case client := <-h.unregister:
  31. if _, ok := h.clients[client]; ok {
  32. delete(h.clients, client)
  33. close(client.send)
  34. }
  35. case message := <-h.broadcast:
  36. for client := range h.clients {
  37. select {
  38. case client.send <- message:
  39. default:
  40. close(client.send)
  41. delete(h.clients, client)
  42. }
  43. }
  44. }
  45. }
  46. }