-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregistry.go
104 lines (78 loc) · 1.76 KB
/
registry.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"sync"
)
// ---------------------------------------------------------------------------
type regntcp struct {
m map[int]*ntcpclient
baton sync.Mutex
}
func (r *regntcp) Put(c *ntcpclient) error {
r.baton.Lock()
defer r.baton.Unlock()
if _, ok := r.m[c.UserID]; ok {
return fmt.Errorf("user(%d) already exists in registry 'regntcp'", c.UserID)
}
r.m[c.UserID] = c
return nil
}
func (r *regntcp) Get(userID int) *ntcpclient {
r.baton.Lock()
defer r.baton.Unlock()
return r.m[userID]
}
func (r *regntcp) Delete(c *ntcpclient) {
r.baton.Lock()
defer r.baton.Unlock()
delete(r.m, c.UserID)
}
// ---------------------------------------------------------------------------
type regnws struct {
m map[int][]*nwsclient
baton sync.Mutex
}
func (r *regnws) Put(c *nwsclient) {
r.baton.Lock()
defer r.baton.Unlock()
r.m[c.UserID] = append(r.m[c.UserID], c)
}
func (r *regnws) Get(userID int) []*nwsclient {
r.baton.Lock()
defer r.baton.Unlock()
return r.m[userID]
}
func (r *regnws) Delete(c *nwsclient) {
r.baton.Lock()
defer r.baton.Unlock()
if len(r.m[c.UserID]) == 1 {
delete(r.m, c.UserID)
return
}
for i, ws := range r.m[c.UserID] {
if ws != c {
continue
}
// get slices of user clients
a := r.m[c.UserID]
// remove connection at index i
a[i] = a[len(a)-1]
a[len(a)-1] = nil
a = a[:len(a)-1]
// set connections
r.m[c.UserID] = a
return
}
}
// ---------------------------------------------------------------------------
var ntcpRegistry regntcp
var nwsRegistry regnws
func registryInit() {
ntcpRegistry = regntcp{
m: map[int]*ntcpclient{},
}
nwsRegistry = regnws{
m: map[int][]*nwsclient{},
}
log.Info("initialized registry storages for ntcpclient and nwsclient structs")
}