A simple TicTacToe app with Golang backend and WebSockets gluing it all together.
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.

53 lines
1.1 KiB

  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. }