-
Notifications
You must be signed in to change notification settings - Fork 1
/
chatroom.go
86 lines (68 loc) · 1.44 KB
/
chatroom.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
package main
import (
"sync"
"log"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type Chatroom struct {
JoinList chan *websocket.Conn
LeaveList chan *websocket.Conn
UserMap map[*websocket.Conn]*User
rw sync.RWMutex
}
var chatroom *Chatroom
func init() {
chatroom = &Chatroom{
JoinList: make(chan *websocket.Conn, 100),
LeaveList: make(chan *websocket.Conn, 100),
UserMap: make(map[*websocket.Conn]*User),
}
go chatroom.welcome()
go chatroom.goodbye()
}
func (c *Chatroom) addUser(newUser *User) {
c.rw.Lock()
defer c.rw.Unlock()
c.UserMap[newUser.connect] = newUser
}
func (c *Chatroom) removeUser(newUser *User) {
c.rw.Lock()
defer c.rw.Unlock()
delete(c.UserMap, newUser.connect)
}
func (c *Chatroom) welcome() {
for ws := range c.JoinList {
newUser := User{
Name: uuid.New().String(),
connect: ws,
}
err := newUser.Send(HelloMessage(&newUser))
if err != nil {
log.Printf("send hello message err: %s\n", err.Error())
c.LeaveList <- ws
return
}
go newUser.listen(c)
c.addUser(&newUser)
}
}
func (c *Chatroom) goodbye() {
for ws := range c.LeaveList {
ws.Close()
c.removeUser(c.UserMap[ws])
}
}
func (c *Chatroom) broadcast(sender *User, message string, self bool) error {
c.rw.RLock()
defer c.rw.RUnlock()
for _, user := range c.UserMap {
if self || sender.Name != user.Name {
err := user.Send(message)
if err != nil {
return err
}
}
}
return nil
}