-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
83 lines (72 loc) · 1.85 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
80
81
82
83
package ftcp
import (
"net"
"github.com/dolfly/core/common/net/udp"
"github.com/dolfly/core/listener"
"github.com/dolfly/core/logger"
md "github.com/dolfly/core/metadata"
admission "github.com/dolfly/x/admission/wrapper"
xnet "github.com/dolfly/x/internal/net"
limiter "github.com/dolfly/x/limiter/traffic/wrapper"
metrics "github.com/dolfly/x/metrics/wrapper"
"github.com/dolfly/x/registry"
stats "github.com/dolfly/x/stats/wrapper"
"github.com/xtaci/tcpraw"
)
func init() {
registry.ListenerRegistry().Register("ftcp", NewListener)
}
type ftcpListener struct {
ln net.Listener
logger logger.Logger
md metadata
options listener.Options
}
func NewListener(opts ...listener.Option) listener.Listener {
options := listener.Options{}
for _, opt := range opts {
opt(&options)
}
return &ftcpListener{
logger: options.Logger,
options: options,
}
}
func (l *ftcpListener) Init(md md.Metadata) (err error) {
if err = l.parseMetadata(md); err != nil {
return
}
var conn net.PacketConn
network := "tcp"
if xnet.IsIPv4(l.options.Addr) {
network = "tcp4"
}
conn, err = tcpraw.Listen(network, l.options.Addr)
if err != nil {
return
}
conn = metrics.WrapPacketConn(l.options.Service, conn)
conn = stats.WrapPacketConn(conn, l.options.Stats)
conn = admission.WrapPacketConn(l.options.Admission, conn)
conn = limiter.WrapPacketConn(l.options.TrafficLimiter, conn)
l.ln = udp.NewListener(
conn,
&udp.ListenConfig{
Backlog: l.md.backlog,
ReadQueueSize: l.md.readQueueSize,
ReadBufferSize: l.md.readBufferSize,
TTL: l.md.ttl,
KeepAlive: true,
Logger: l.logger,
})
return
}
func (l *ftcpListener) Accept() (conn net.Conn, err error) {
return l.ln.Accept()
}
func (l *ftcpListener) Addr() net.Addr {
return l.ln.Addr()
}
func (l *ftcpListener) Close() error {
return l.ln.Close()
}