-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_hub.go
61 lines (49 loc) · 1.74 KB
/
tcp_hub.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
package internet
import (
"context"
"v2ray.com/core/common/net"
)
var (
transportListenerCache = make(map[string]ListenFunc)
)
func RegisterTransportListener(protocol string, listener ListenFunc) error {
if _, found := transportListenerCache[protocol]; found {
return newError(protocol, " listener already registered.").AtError()
}
transportListenerCache[protocol] = listener
return nil
}
type ConnHandler func(Connection)
type ListenFunc func(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error)
type Listener interface {
Close() error
Addr() net.Addr
}
func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) {
if settings == nil {
s, err := ToMemoryStreamConfig(nil)
if err != nil {
return nil, newError("failed to create default stream settings").Base(err)
}
settings = s
}
if address.Family().IsDomain() && address.Domain() == "localhost" {
address = net.LocalHostIP
}
protocol := settings.ProtocolName
listenFunc := transportListenerCache[protocol]
if listenFunc == nil {
return nil, newError(protocol, " listener not registered.").AtError()
}
listener, err := listenFunc(ctx, address, port, settings, handler)
if err != nil {
return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
}
return listener, nil
}
func ListenSystem(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.Listener, error) {
return effectiveListener.Listen(ctx, addr, sockopt)
}
func ListenSystemPacket(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.PacketConn, error) {
return effectiveListener.ListenPacket(ctx, addr, sockopt)
}