-
Notifications
You must be signed in to change notification settings - Fork 0
/
room.go
61 lines (53 loc) · 1.05 KB
/
room.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/json"
"fmt"
"sync"
)
type Room struct {
sync.Mutex
hub *Hub
players map[*Client]bool
broadcast chan gameMessage
// Unregister requests from clients.
unregister chan *Client
waiting bool
}
func newRoom(hub *Hub, client *Client) *Room {
return &Room{
hub: hub,
players: make(map[*Client]bool),
waiting: true,
broadcast: make(chan gameMessage),
unregister: make(chan *Client),
}
}
func (r *Room) run() {
for {
select {
case message := <-r.broadcast:
val, err := json.Marshal(message)
fmt.Print("borad casting message ", message, "\n")
if err != nil {
fmt.Print(err.Error())
}
for client := range r.players {
r.hub.Lock()
select {
case client.send <- val:
default:
close(client.send)
delete(r.players, client)
}
r.hub.Unlock()
if message.Event == "abandon" {
r.hub.delete <- r
}
}
case client := <-r.unregister:
fmt.Println("unregister request came")
client.conn.Close()
delete(r.players, client)
}
}
}