tcp_hub.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package internet
  2. import (
  3. "errors"
  4. "net"
  5. "sync"
  6. "github.com/v2ray/v2ray-core/common/log"
  7. v2net "github.com/v2ray/v2ray-core/common/net"
  8. )
  9. var (
  10. ErrorClosedConnection = errors.New("Connection already closed.")
  11. KCPListenFunc ListenFunc
  12. TCPListenFunc ListenFunc
  13. RawTCPListenFunc ListenFunc
  14. )
  15. type ListenFunc func(address v2net.Address, port v2net.Port) (Listener, error)
  16. type Listener interface {
  17. Accept() (Connection, error)
  18. Close() error
  19. Addr() net.Addr
  20. }
  21. type TCPHub struct {
  22. sync.Mutex
  23. listener Listener
  24. connCallback ConnectionHandler
  25. accepting bool
  26. }
  27. func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandler, settings *StreamSettings) (*TCPHub, error) {
  28. var listener Listener
  29. var err error
  30. switch {
  31. case settings.IsCapableOf(StreamConnectionTypeTCP):
  32. listener, err = TCPListenFunc(address, port)
  33. case settings.IsCapableOf(StreamConnectionTypeKCP):
  34. listener, err = KCPListenFunc(address, port)
  35. case settings.IsCapableOf(StreamConnectionTypeRawTCP):
  36. listener, err = RawTCPListenFunc(address, port)
  37. default:
  38. err = ErrUnsupportedStreamType
  39. }
  40. if err != nil {
  41. return nil, err
  42. }
  43. hub := &TCPHub{
  44. listener: listener,
  45. connCallback: callback,
  46. }
  47. go hub.start()
  48. return hub, nil
  49. }
  50. func (this *TCPHub) Close() {
  51. this.accepting = false
  52. this.listener.Close()
  53. }
  54. func (this *TCPHub) start() {
  55. this.accepting = true
  56. for this.accepting {
  57. conn, err := this.listener.Accept()
  58. if err != nil {
  59. if this.accepting {
  60. log.Warning("Listener: Failed to accept new TCP connection: ", err)
  61. }
  62. continue
  63. }
  64. log.Info("Handling connection from ", conn.RemoteAddr())
  65. go this.connCallback(conn)
  66. }
  67. }