-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
85 lines (77 loc) · 1.61 KB
/
hub.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
package main
import "encoding/json"
// Hub 核心结构体
type Hub struct {
// 注册客户端
clients map[*Client]bool
// 消息通道
broadcast chan Broad
register chan *Client
// 卸载客户端
unregister chan *Client
// Uid from clients.
userINFO map[string]*UserInfo
}
func newHub() *Hub {
return &Hub{
broadcast: make(chan Broad),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
userINFO: make(map[string]*UserInfo),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
delete(h.userINFO, client.uuid)
close(client.send)
}
//更新客户端列表
var msg Msg
var users = make(map[string]string)
for _, vlue := range h.userINFO {
users[vlue.UUID] = vlue.NickName
}
msg.User = users
msg.Code = 200
msg.Rtype = 2
msgJSON, err := json.Marshal(msg)
if err == nil {
for client := range h.clients {
select {
case client.send <- msgJSON:
default:
close(client.send)
delete(h.clients, client)
}
}
}
case broad := <-h.broadcast:
if broad.Rtype == 1 {
for client := range h.clients {
select {
case client.send <- broad.Content:
default:
close(client.send)
delete(h.clients, client)
}
}
}
if broad.Rtype == 2 {
client := broad.Client
select {
case client.send <- broad.Content:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}