-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtalkie.go
87 lines (75 loc) · 1.28 KB
/
talkie.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 talkie
import (
"bufio"
"os"
"strings"
"sync"
)
const username = "User"
var exitMap = map[string]bool{
"BYE": true,
"QUIT": true,
"exit": true,
}
type Talkie struct {
broker *Broker
roles map[string]*Role
group sync.WaitGroup
stdin *bufio.Reader
}
func New() *Talkie {
return &Talkie{
broker: NewBroker(),
roles: make(map[string]*Role),
stdin: bufio.NewReader(os.Stdin),
}
}
func (t *Talkie) Start() {
t.broker.Start()
for _, role := range t.roles {
role.Start(t.broker, &t.group)
}
t.ReadInput()
}
func (t *Talkie) ReadInput() {
user := t.NewRole(username, White, nil)
for {
text, _ := t.stdin.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
if exitMap[text] {
t.Close()
return
}
t.Broadcast(Message{
Sender: user,
Content: text,
})
}
}
func (t *Talkie) Broadcast(msg Message) {
t.broker.Send(msg)
for _, role := range t.roles {
role.Recieve(msg)
}
}
func (t *Talkie) Close() {
for _, role := range t.roles {
role.Close()
}
t.broker.Close()
}
func (t *Talkie) Wait() {
t.group.Wait()
}
func (t *Talkie) add(role *Role) bool {
_, found := t.roles[role.Name]
if found {
return false
}
t.roles[role.Name] = role
return true
}
func (t *Talkie) remove(role *Role) {
delete(t.roles, role.Name)
role.Close()
}