forked from 1058168853/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsesmgr.go
126 lines (89 loc) · 1.93 KB
/
sesmgr.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package cellnet
import (
"sync"
"sync/atomic"
)
// 会话访问
type SessionAccessor interface {
// 获取一个连接
GetSession(int64) Session
// 遍历连接
VisitSession(func(Session) bool)
// 连接数量
SessionCount() int
// 关闭所有连接
CloseAllSession()
}
// 完整功能的会话管理
type SessionManager interface {
SessionAccessor
Add(Session)
Remove(Session)
}
type SessionManagerImplement struct {
sesMap map[int64]Session
sesIDAcc int64
sesMapGuard sync.RWMutex
}
const totalTryCount = 100
func (self *SessionManagerImplement) Add(ses Session) {
self.sesMapGuard.Lock()
defer self.sesMapGuard.Unlock()
var tryCount int = totalTryCount
var id int64
// id翻越处理
for tryCount > 0 {
id = atomic.AddInt64(&self.sesIDAcc, 1)
if _, ok := self.sesMap[id]; !ok {
break
}
tryCount--
}
if tryCount == 0 {
log.Warnln("sessionID override!", id)
}
ses.(interface {
SetID(int64)
}).SetID(id)
self.sesMap[id] = ses
}
func (self *SessionManagerImplement) Remove(ses Session) {
self.sesMapGuard.Lock()
delete(self.sesMap, ses.ID())
self.sesMapGuard.Unlock()
}
// 获得一个连接
func (self *SessionManagerImplement) GetSession(id int64) Session {
self.sesMapGuard.RLock()
defer self.sesMapGuard.RUnlock()
v, ok := self.sesMap[id]
if ok {
return v
}
return nil
}
func (self *SessionManagerImplement) VisitSession(callback func(Session) bool) {
self.sesMapGuard.RLock()
defer self.sesMapGuard.RUnlock()
for _, ses := range self.sesMap {
if !callback(ses) {
break
}
}
}
func (self *SessionManagerImplement) CloseAllSession() {
self.VisitSession(func(ses Session) bool {
ses.Close()
return true
})
}
func (self *SessionManagerImplement) SessionCount() int {
self.sesMapGuard.Lock()
defer self.sesMapGuard.Unlock()
return len(self.sesMap)
}
func NewSessionManager() SessionManager {
return &SessionManagerImplement{
sesMap: make(map[int64]Session),
}
}