-
Notifications
You must be signed in to change notification settings - Fork 36
/
listener.go
79 lines (72 loc) · 1.72 KB
/
listener.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
package rudp
import (
"net"
"sync"
)
func NewListener(conn *net.UDPConn) *RudpListener {
listen := &RudpListener{conn: conn,
newRudpConn: make(chan *RudpConn, 1024),
newRudpErr: make(chan error, 12),
rudpConnMap: make(map[string]*RudpConn)}
go listen.run()
return listen
}
type RudpListener struct {
conn *net.UDPConn
lock sync.RWMutex
newRudpConn chan *RudpConn
newRudpErr chan error
rudpConnMap map[string]*RudpConn
}
//net listener interface
func (this *RudpListener) Accept() (net.Conn, error) { return this.AcceptRudp() }
func (this *RudpListener) Close() error {
this.CloseAllRudp()
return this.conn.Close()
}
func (this *RudpListener) Addr() net.Addr { return this.conn.LocalAddr() }
func (this *RudpListener) CloseRudp(addr string) {
this.lock.Lock()
delete(this.rudpConnMap, addr)
this.lock.Unlock()
}
func (this *RudpListener) CloseAllRudp() {
this.lock.Lock()
for _, rconn := range this.rudpConnMap {
rconn.closef = nil
rconn.Close()
}
this.lock.Unlock()
}
func (this *RudpListener) AcceptRudp() (*RudpConn, error) {
select {
case c := <-this.newRudpConn:
return c, nil
case e := <-this.newRudpErr:
return nil, e
}
}
func (this *RudpListener) run() {
data := make([]byte, MAX_PACKAGE)
for {
n, remoteAddr, err := this.conn.ReadFromUDP(data)
if err != nil {
this.CloseAllRudp()
this.newRudpErr <- err
return
}
this.lock.RLock()
rudpConn, ok := this.rudpConnMap[remoteAddr.String()]
this.lock.RUnlock()
if !ok {
rudpConn = NewUnConn(this.conn, remoteAddr, New(), this.CloseRudp)
this.lock.Lock()
this.rudpConnMap[remoteAddr.String()] = rudpConn
this.lock.Unlock()
this.newRudpConn <- rudpConn
}
bts := make([]byte, n)
copy(bts, data[:n])
rudpConn.in <- bts
}
}