1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/transport/internet/tcp_hub.go
Darien Raymond a6d81cc56d
api doc
2018-12-03 23:39:21 +01:00

68 lines
1.9 KiB
Go

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
}
// ListenSystem listens on a local address for incoming TCP connections.
//
// v2ray:api:beta
func ListenSystem(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.Listener, error) {
return effectiveListener.Listen(ctx, addr, sockopt)
}
// ListenSystemPacket listens on a local address for incoming UDP connections.
//
// v2ray:api:beta
func ListenSystemPacket(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.PacketConn, error) {
return effectiveListener.ListenPacket(ctx, addr, sockopt)
}