-
Notifications
You must be signed in to change notification settings - Fork 24
/
connection_pool.go
91 lines (80 loc) · 1.83 KB
/
connection_pool.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
package sipnet
import (
"bytes"
"io"
"net"
"sync"
"time"
)
func (l *Listener) getUDPConnFromPool(address net.Addr) *Conn {
l.udpPoolMutex.Lock()
defer l.udpPoolMutex.Unlock()
conn, found := l.udpPool[address.String()]
if !found {
conn = &Conn{
Transport: "udp",
Listener: l,
Conn: l.udpListener,
Address: address,
UdpReceiver: make(chan []byte),
Closed: false,
Locked: false,
WriteBuffer: new(bytes.Buffer),
ReadMessage: make(chan interface{}),
LastMessage: time.Now(),
ReceivedBranches: make(map[string]time.Time),
BranchMutex: new(sync.Mutex),
}
l.udpPool[address.String()] = conn
go conn.udpReader()
go conn.branchJanitor()
go l.readRequests(conn)
}
return conn
}
func (l *Listener) registerTCPConn(netConn net.Conn) {
conn := &Conn{
Transport: "tcp",
Listener: l,
Conn: netConn,
Address: netConn.RemoteAddr(),
UdpReceiver: nil,
Closed: false,
Locked: false,
WriteBuffer: new(bytes.Buffer),
ReadMessage: make(chan interface{}),
LastMessage: time.Time{},
ReceivedBranches: make(map[string]time.Time),
BranchMutex: new(sync.Mutex),
}
go conn.tcpReader()
go conn.branchJanitor()
go l.readRequests(conn)
}
func (l *Listener) readRequests(conn *Conn) {
for {
req, err := conn.readRequest()
l.requestChannel <- requestPackage{
conn: conn,
req: req,
err: err,
}
if err == io.EOF {
return
}
}
}
func (l *Listener) udpJanitor() {
for {
time.Sleep(time.Second * 10)
l.udpPoolMutex.Lock()
for address, conn := range l.udpPool {
if time.Now().Sub(conn.LastMessage) > time.Second*30 {
// Disconnect
conn.Close()
delete(l.udpPool, address)
}
}
l.udpPoolMutex.Unlock()
}
}