-
Notifications
You must be signed in to change notification settings - Fork 0
/
room.go
66 lines (50 loc) · 1.14 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
package server
import (
"sync"
"github.com/Sirupsen/logrus"
"github.com/pkg/errors"
"github.com/SierraSoftworks/chat/protocol"
)
type Room struct {
Clients []*Client
lock sync.Mutex
}
func (r *Room) Join(cl *Client) error {
r.lock.Lock()
defer r.lock.Unlock()
for _, c := range r.Clients {
if c == cl {
return errors.New("client already in the room")
}
}
r.Clients = append(r.Clients, cl)
logrus.Debug("Client joined the room")
return nil
}
func (r *Room) Leave(cl *Client) error {
r.lock.Lock()
defer r.lock.Unlock()
for i, c := range r.Clients {
if c == cl {
r.Clients = append(r.Clients[:i], r.Clients[i+1:]...)
logrus.Debug("Client left the room")
return nil
}
}
return errors.New("client not found in room")
}
func (r *Room) Broadcast(cmd *protocol.RawCommand) error {
r.lock.Lock()
defer r.lock.Unlock()
logrus.WithField("cmd", cmd).Debug("Broadcasting command")
sendErrors := map[*Client]error{}
for _, cl := range r.Clients {
if err := cl.Send(cmd); err != nil {
sendErrors[cl] = err
}
}
if len(sendErrors) > 0 {
return errors.New("failed to broadcast to all clients")
}
return nil
}