-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcliUserManager.go
More file actions
130 lines (105 loc) · 2.41 KB
/
cliUserManager.go
File metadata and controls
130 lines (105 loc) · 2.41 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package juice
import (
"sync"
"time"
)
var ucm *userClientManager
var OnlineUsers map[int]time.Time
var changeUserStatusChan chan struct {
uid int
status bool
}
var onceUCM sync.Once
type userClientManager struct {
ucs map[int]*UserClient
// future : create a user lock-pool don't depend this
sync.RWMutex
}
type UserClient struct {
sync.Mutex
Uid int
Clients map[uint32]*Client
}
func GetUserCliManager() *userClientManager {
onceUCM.Do(func() {
ucm = &userClientManager{
ucs: make(map[int]*UserClient),
}
OnlineUsers = make(map[int]time.Time)
changeUserStatusChan = make(chan struct {
uid int
status bool
}, 100)
//状态更改器
go ucm.userStatusCustomer()
})
return ucm
}
func (ucm *userClientManager) GetOnlineUsers() map[int]time.Time {
ucm.RLock()
defer ucm.RUnlock()
return OnlineUsers
}
func (ucm *userClientManager) GetUserClients() map[int]*UserClient {
ucm.RLock()
defer ucm.RUnlock()
return ucm.ucs
}
func (ucm *userClientManager) GetUserClient(uid int) (uc *UserClient, ok bool) {
ucm.RLock()
defer ucm.RUnlock()
uc, ok = ucm.ucs[uid]
return
}
func (ucm *userClientManager) getOnlineUsers() map[int]time.Time {
return OnlineUsers
}
func (ucm *userClientManager) getUserClient(uid int) (ucs *UserClient, ok bool) {
ucs, ok = ucm.ucs[uid]
return
}
// up observer mode | locked from cliManager ->func addClient
func (ucm *userClientManager) AddClient(cli *Client) {
if uc, ok := ucm.getUserClient(cli.Uid); ok {
uc.Clients[cli.UUID] = cli
} else {
ucm.addUserClient(cli)
}
}
func (ucm *userClientManager) addUserClient(cli *Client) {
ucm.ucs[cli.Uid] = &UserClient{
Uid: cli.Uid,
Clients: map[uint32]*Client{
cli.UUID: cli,
},
}
//user online
ucm.getOnlineUsers()[cli.Uid] = time.Now()
changeUserStatusChan <- struct {
uid int
status bool
}{uid: cli.Uid, status: true}
}
// down observer mode | locked from cliManager ->func addClient
func (ucm *userClientManager) RemoveClient(cli *Client) {
delete(ucm.ucs[cli.Uid].Clients, cli.UUID)
if len(ucm.ucs[cli.Uid].Clients) == 0 {
//user offline
delete(ucm.ucs, cli.Uid)
delete(ucm.getOnlineUsers(), cli.Uid)
changeUserStatusChan <- struct {
uid int
status bool
}{uid: cli.Uid, status: false}
}
}
// future : buffer
func (ucm *userClientManager) userStatusCustomer() {
for c := range changeUserStatusChan {
if c.status {
// user up
} else {
// user down
}
}
}