-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.go
executable file
·83 lines (74 loc) · 1.77 KB
/
manager.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
package bifrost
import (
"fmt"
"net"
"sync"
"time"
)
type connectionManager struct {
connectionsLock *sync.Mutex
connections map[string]*Connection
socket *Socket
reaper *time.Ticker
control chan bool
}
func newConnectionManager(s *Socket) *connectionManager {
newConnectionManager := connectionManager{}
newConnectionManager.connections = make(map[string]*Connection)
newConnectionManager.socket = s
newConnectionManager.reaper = time.NewTicker(time.Second * 5)
newConnectionManager.control = make(chan bool, 1)
newConnectionManager.connectionsLock = &sync.Mutex{}
//go newConnectionManager.disconnected()
return &newConnectionManager
}
func (cm *connectionManager) add(c *Connection) bool {
cm.connectionsLock.Lock()
defer cm.connectionsLock.Unlock()
connKey := c.key()
_, ok := cm.connections[connKey]
if ok == false {
cm.connections[connKey] = c
return true
}
return false
}
func (cm *connectionManager) remove(c *Connection) bool {
cm.connectionsLock.Lock()
defer cm.connectionsLock.Unlock()
_, ok := cm.connections[c.key()]
if ok == true {
delete(cm.connections, c.key())
return true
}
return false
}
func (cm *connectionManager) disconnected() {
for range cm.reaper.C {
select {
case <-cm.control:
return
default:
cm.connectionsLock.Lock()
for _, v := range cm.connections {
if v.lastHeardSeconds() >= cm.socket.timeout {
ne := NewEvent(1, v, nil)
cm.socket.Events <- ne
cm.remove(v)
}
}
cm.connectionsLock.Unlock()
}
}
}
func (cm *connectionManager) find(r *net.UDPAddr) *Connection {
cm.connectionsLock.Lock()
defer cm.connectionsLock.Unlock()
key := fmt.Sprintf("%s:%d", r.IP, r.Port)
for k, v := range cm.connections {
if key == k {
return v
}
}
return nil
}