forked from tim1020/godaemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
55 lines (47 loc) · 977 Bytes
/
conn.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
package godaemon
import (
"net"
"sync"
"time"
)
type ConnectionManager struct {
sync.WaitGroup
Counter int
mux sync.Mutex
idleConns map[string]net.Conn
}
func newConnectionManager() *ConnectionManager {
cm := &ConnectionManager{}
cm.WaitGroup = sync.WaitGroup{}
cm.idleConns = make(map[string]net.Conn)
return cm
}
func (cm *ConnectionManager) add(delta int) {
cm.Counter += delta
cm.WaitGroup.Add(delta)
}
func (cm *ConnectionManager) done() {
cm.Counter--
cm.WaitGroup.Done()
}
func (cm *ConnectionManager) close(t time.Duration) {
cm.mux.Lock()
dt := time.Now().Add(t)
for _, c := range cm.idleConns {
c.SetDeadline(dt)
}
cm.idleConns = nil
cm.mux.Unlock()
cm.WaitGroup.Wait()
return
}
func (cm *ConnectionManager) rmIdleConns(key string) {
cm.mux.Lock()
delete(cm.idleConns, key)
cm.mux.Unlock()
}
func (cm *ConnectionManager) addIdleConns(key string, conn net.Conn) {
cm.mux.Lock()
cm.idleConns[key] = conn
cm.mux.Unlock()
}