-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathtransport.go
101 lines (89 loc) · 1.95 KB
/
transport.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
92
93
94
95
96
97
98
99
100
101
package snmpgo
import (
"net"
"sync"
"time"
)
type transport interface {
Listen() (interface{}, error)
Read(interface{}, []byte) (int, net.Addr, message, error)
Write(interface{}, []byte, net.Addr) error
Close(interface{}) error
}
type packetTransport struct {
conn net.PacketConn
lock *sync.Mutex
anchor chan struct{}
network string
localAddr string
writeTimeout time.Duration
}
func (t *packetTransport) Listen() (interface{}, error) {
t.lock.Lock()
c := t.conn
t.lock.Unlock()
if c != nil {
<-t.anchor
return nil, nil
}
c, err := net.ListenPacket(t.network, t.localAddr)
t.lock.Lock()
t.conn = c
t.lock.Unlock()
return c, err
}
func (t *packetTransport) Read(conn interface{}, buf []byte) (num int, src net.Addr, msg message, err error) {
c := conn.(net.PacketConn)
for {
num, src, err = c.ReadFrom(buf)
if err != nil {
if e, ok := err.(net.Error); ok && e.Temporary() {
continue
}
return
}
pkt := make([]byte, num)
copy(pkt, buf)
msg, _, err = unmarshalMessage(pkt)
return
}
}
func (t *packetTransport) Write(conn interface{}, pkt []byte, dst net.Addr) error {
c := conn.(net.PacketConn)
if err := c.SetWriteDeadline(time.Now().Add(t.writeTimeout)); err != nil {
return err
}
for {
if _, err := c.WriteTo(pkt, dst); err != nil {
if e, ok := err.(net.Error); ok && e.Temporary() && !e.Timeout() {
continue
}
return err
}
return nil
}
}
func (t *packetTransport) Close(_ interface{}) error {
t.lock.Lock()
defer t.lock.Unlock()
if c := t.conn; c != nil {
t.conn = nil
t.anchor <- struct{}{}
return c.Close()
}
return nil
}
func newTransport(args *ServerArguments) transport {
switch args.Network {
case "udp", "udp4", "udp6":
return &packetTransport{
lock: new(sync.Mutex),
anchor: make(chan struct{}, 0),
network: args.Network,
localAddr: args.LocalAddr,
writeTimeout: args.WriteTimeout,
}
default:
return nil
}
}