tcp_hub.go 2.0 KB

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