-
Notifications
You must be signed in to change notification settings - Fork 16
/
bucket.go
64 lines (57 loc) · 1.08 KB
/
bucket.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
package tcp
import (
"sync"
)
//TCPConnBucket 用来存放和管理TCPConn连接
type TCPConnBucket struct {
m map[string]*TCPConn
mu *sync.RWMutex
}
func NewTCPConnBucket() *TCPConnBucket {
tcb := &TCPConnBucket{
m: make(map[string]*TCPConn),
mu: new(sync.RWMutex),
}
return tcb
}
func (b *TCPConnBucket) Put(id string, c *TCPConn) {
b.mu.Lock()
if conn, ok := b.m[id]; ok {
conn.Close()
}
b.m[id] = c
b.mu.Unlock()
}
func (b *TCPConnBucket) Get(id string) *TCPConn {
b.mu.RLock()
defer b.mu.RUnlock()
if conn, ok := b.m[id]; ok {
return conn
}
return nil
}
func (b *TCPConnBucket) Delete(id string) {
b.mu.Lock()
delete(b.m, id)
b.mu.Unlock()
}
func (b *TCPConnBucket) GetAll() map[string]*TCPConn {
b.mu.RLock()
defer b.mu.RUnlock()
m := make(map[string]*TCPConn, len(b.m))
for k, v := range b.m {
m[k] = v
}
return m
}
func (b *TCPConnBucket) removeClosedTCPConn() {
removeKey := make(map[string]struct{})
for key, conn := range b.GetAll() {
if conn.IsClosed() {
removeKey[key] = struct{}{}
}
}
for key := range removeKey {
b.Delete(key)
}
}