forked from davyxu/cellnet
/
sesmgr.go
92 lines (61 loc) · 1.63 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
package peer
import (
"github.com/szdartou/cellnet"
"sync"
"sync/atomic"
)
// 完整功能的会话管理
type SessionManager interface {
cellnet.SessionAccessor
Add(cellnet.Session)
Remove(cellnet.Session)
Count() int
// 设置ID开始的号
SetIDBase(base int64)
}
type CoreSessionManager struct {
sesById sync.Map // 使用Id关联会话
sesIDGen int64 // 记录已经生成的会话ID流水号
count int64 // 记录当前在使用的会话数量
}
func (self *CoreSessionManager) SetIDBase(base int64) {
atomic.StoreInt64(&self.sesIDGen, base)
}
func (self *CoreSessionManager) Count() int {
return int(atomic.LoadInt64(&self.count))
}
func (self *CoreSessionManager) Add(ses cellnet.Session) {
id := atomic.AddInt64(&self.sesIDGen, 1)
atomic.AddInt64(&self.count, 1)
ses.(interface {
SetID(int64)
}).SetID(id)
self.sesById.Store(id, ses)
}
func (self *CoreSessionManager) Remove(ses cellnet.Session) {
self.sesById.Delete(ses.ID())
atomic.AddInt64(&self.count, -1)
}
// 获得一个连接
func (self *CoreSessionManager) GetSession(id int64) cellnet.Session {
if v, ok := self.sesById.Load(id); ok {
return v.(cellnet.Session)
}
return nil
}
func (self *CoreSessionManager) VisitSession(callback func(cellnet.Session) bool) {
self.sesById.Range(func(key, value interface{}) bool {
return callback(value.(cellnet.Session))
})
}
func (self *CoreSessionManager) CloseAllSession() {
self.VisitSession(func(ses cellnet.Session) bool {
ses.Close()
return true
})
}
// 活跃的会话数量
func (self *CoreSessionManager) SessionCount() int {
v := atomic.LoadInt64(&self.count)
return int(v)
}