1
0

pool.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package main
  2. import "fmt"
  3. type Pool struct {
  4. Register chan *Client
  5. Unregister chan *Client
  6. Clients map[*Client]bool
  7. Broadcast chan Message
  8. }
  9. func NewPool() *Pool {
  10. return &Pool{
  11. Register: make(chan *Client),
  12. Unregister: make(chan *Client),
  13. Clients: make(map[*Client]bool),
  14. Broadcast: make(chan Message),
  15. }
  16. }
  17. func (pool *Pool) Start() {
  18. for {
  19. select {
  20. case client := <-pool.Register:
  21. pool.Clients[client] = true
  22. fmt.Println("Size of Connection Pool: ", len(pool.Clients))
  23. for client, _ := range pool.Clients {
  24. fmt.Println(client)
  25. client.Conn.WriteJSON(Message{Type: 1, Body: fmt.Sprintf("New User %v Joined...", &client.ID)})
  26. }
  27. break
  28. case client := <-pool.Unregister:
  29. delete(pool.Clients, client)
  30. fmt.Println("Size of Connection Pool: ", len(pool.Clients))
  31. for client, _ := range pool.Clients {
  32. client.Conn.WriteJSON(Message{Type: 1, Body: fmt.Sprintf("User %v Disconnected...", &client.ID)})
  33. }
  34. break
  35. case message := <-pool.Broadcast:
  36. fmt.Println("Sending message to all clients in Pool")
  37. for client, _ := range pool.Clients {
  38. if err := client.Conn.WriteJSON(message); err != nil {
  39. fmt.Println(err)
  40. return
  41. }
  42. }
  43. }
  44. }
  45. }