-
Notifications
You must be signed in to change notification settings - Fork 0
/
room.go
87 lines (70 loc) · 1.72 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"fmt"
"github.com/google/uuid"
)
const welcomeMessage = "%s joined the room"
type Room struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
clients map[*Client]bool
register chan *Client
unregister chan *Client
broadcast chan *Message
Private bool `json:"private"`
}
// NewRoom creates a new Room
func NewRoom(name string, private bool) *Room {
return &Room{
ID: uuid.New(),
Name: name,
clients: make(map[*Client]bool),
register: make(chan *Client),
unregister: make(chan *Client),
broadcast: make(chan *Message),
Private: private,
}
}
// RunRoom runs our room, accepting various requests
func (room *Room) RunRoom() {
for {
select {
case client := <-room.register:
room.registerClientInRoom(client)
case client := <-room.unregister:
room.unregisterClientInRoom(client)
case message := <-room.broadcast:
room.broadcastToClientsInRoom(message.encode())
}
}
}
func (room *Room) registerClientInRoom(client *Client) {
if !room.Private {
room.notifyClientJoined(client)
}
room.clients[client] = true
}
func (room *Room) unregisterClientInRoom(client *Client) {
if _, ok := room.clients[client]; ok {
delete(room.clients, client)
}
}
func (room *Room) broadcastToClientsInRoom(message []byte) {
for client := range room.clients {
client.send <- message
}
}
func (room *Room) notifyClientJoined(client *Client) {
message := &Message{
Action: SendMessageAction,
Target: room,
Message: fmt.Sprintf(welcomeMessage, client.GetName()),
}
room.broadcastToClientsInRoom(message.encode())
}
func (room *Room) GetId() string {
return room.ID.String()
}
func (room *Room) GetName() string {
return room.Name
}