forked from bluenviron/gomavlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpointserver.go
120 lines (97 loc) · 2.48 KB
/
endpointserver.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package gomavlib
import (
"fmt"
"io"
"net"
"github.com/aler9/gomavlib/pkg/udplistener"
)
type endpointServerConf interface {
isUDP() bool
getAddress() string
init() (Endpoint, error)
}
// EndpointTCPServer sets up a endpoint that works with a TCP server.
// TCP is fit for routing frames through the internet, but is not the most
// appropriate way for transferring frames from a UAV to a GCS, since it does
// not allow frame losses.
type EndpointTCPServer struct {
// listen address, example: 0.0.0.0:5600
Address string
}
func (EndpointTCPServer) isUDP() bool {
return false
}
func (conf EndpointTCPServer) getAddress() string {
return conf.Address
}
// EndpointUDPServer sets up a endpoint that works with an UDP server.
// This is the most appropriate way for transferring frames from a UAV to a GCS
// if they are connected to the same network.
type EndpointUDPServer struct {
// listen address, example: 0.0.0.0:5600
Address string
}
func (EndpointUDPServer) isUDP() bool {
return true
}
func (conf EndpointUDPServer) getAddress() string {
return conf.Address
}
type endpointServer struct {
conf endpointServerConf
listener net.Listener
// in
terminate chan struct{}
}
func (conf EndpointTCPServer) init() (Endpoint, error) {
return initEndpointServer(conf)
}
func (conf EndpointUDPServer) init() (Endpoint, error) {
return initEndpointServer(conf)
}
func initEndpointServer(conf endpointServerConf) (Endpoint, error) {
_, _, err := net.SplitHostPort(conf.getAddress())
if err != nil {
return nil, fmt.Errorf("invalid address")
}
var listener net.Listener
if conf.isUDP() {
listener, err = udplistener.New("udp4", conf.getAddress())
} else {
listener, err = net.Listen("tcp4", conf.getAddress())
}
if err != nil {
return nil, err
}
t := &endpointServer{
conf: conf,
listener: listener,
terminate: make(chan struct{}),
}
return t, nil
}
func (t *endpointServer) isEndpoint() {}
func (t *endpointServer) Conf() EndpointConf {
return t.conf
}
func (t *endpointServer) Close() error {
close(t.terminate)
t.listener.Close()
return nil
}
func (t *endpointServer) Accept() (string, io.ReadWriteCloser, error) {
rawConn, err := t.listener.Accept()
// wait termination, do not report errors
if err != nil {
<-t.terminate
return "", nil, errorTerminated
}
label := fmt.Sprintf("%s:%s", func() string {
if t.conf.isUDP() {
return "udp"
}
return "tcp"
}(), rawConn.RemoteAddr())
conn := &netTimedConn{rawConn}
return label, conn, nil
}