tcp_hub.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. if settings.IsCapableOf(StreamConnectionTypeKCP) {
  31. listener, err = KCPListenFunc(address, port)
  32. } else if settings.IsCapableOf(StreamConnectionTypeTCP) {
  33. listener, err = TCPListenFunc(address, port)
  34. } else {
  35. listener, err = RawTCPListenFunc(address, port)
  36. }
  37. if err != nil {
  38. return nil, err
  39. }
  40. hub := &TCPHub{
  41. listener: listener,
  42. connCallback: callback,
  43. }
  44. go hub.start()
  45. return hub, nil
  46. }
  47. func (this *TCPHub) Close() {
  48. this.accepting = false
  49. this.listener.Close()
  50. }
  51. func (this *TCPHub) start() {
  52. this.accepting = true
  53. for this.accepting {
  54. conn, err := this.listener.Accept()
  55. if err != nil {
  56. if this.accepting {
  57. log.Warning("Listener: Failed to accept new TCP connection: ", err)
  58. }
  59. continue
  60. }
  61. log.Info("Handling connection from ", conn.RemoteAddr())
  62. go this.connCallback(conn)
  63. }
  64. }