tcp_hub.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package internet
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. var (
  7. transportListenerCache = make(map[string]ListenFunc)
  8. )
  9. func RegisterTransportListener(protocol string, listener ListenFunc) error {
  10. if _, found := transportListenerCache[protocol]; found {
  11. return newError(protocol, " listener already registered.").AtError()
  12. }
  13. transportListenerCache[protocol] = listener
  14. return nil
  15. }
  16. type ConnHandler func(Connection)
  17. type ListenFunc func(ctx context.Context, address net.Address, port net.Port, handler ConnHandler) (Listener, error)
  18. type Listener interface {
  19. Close() error
  20. Addr() net.Addr
  21. }
  22. func ListenTCP(ctx context.Context, address net.Address, port net.Port, handler ConnHandler) (Listener, error) {
  23. settings := StreamSettingsFromContext(ctx)
  24. protocol := settings.ProtocolName
  25. listenFunc := transportListenerCache[protocol]
  26. if listenFunc == nil {
  27. return nil, newError(protocol, " listener not registered.").AtError()
  28. }
  29. listener, err := listenFunc(ctx, address, port, handler)
  30. if err != nil {
  31. return nil, newError("failed to listen on address: ", address, ":", port).Base(err)
  32. }
  33. return listener, nil
  34. }