tcp.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package hub
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "net"
  6. "sync"
  7. "github.com/v2ray/v2ray-core/common/log"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. )
  10. var (
  11. ErrorClosedConnection = errors.New("Connection already closed.")
  12. )
  13. type TCPHub struct {
  14. sync.Mutex
  15. listener net.Listener
  16. connCallback ConnectionHandler
  17. accepting bool
  18. }
  19. func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandler, tlsConfig *tls.Config) (*TCPHub, error) {
  20. listener, err := net.ListenTCP("tcp", &net.TCPAddr{
  21. IP: address.IP(),
  22. Port: int(port),
  23. Zone: "",
  24. })
  25. if err != nil {
  26. return nil, err
  27. }
  28. var hub *TCPHub
  29. if tlsConfig != nil {
  30. tlsListener := tls.NewListener(listener, tlsConfig)
  31. hub = &TCPHub{
  32. listener: tlsListener,
  33. connCallback: callback,
  34. }
  35. } else {
  36. hub = &TCPHub{
  37. listener: listener,
  38. connCallback: callback,
  39. }
  40. }
  41. go hub.start()
  42. return hub, nil
  43. }
  44. func (this *TCPHub) Close() {
  45. this.accepting = false
  46. this.listener.Close()
  47. }
  48. func (this *TCPHub) start() {
  49. this.accepting = true
  50. for this.accepting {
  51. conn, err := this.listener.Accept()
  52. if err != nil {
  53. if this.accepting {
  54. log.Warning("Listener: Failed to accept new TCP connection: ", err)
  55. }
  56. continue
  57. }
  58. go this.connCallback(&Connection{
  59. dest: conn.RemoteAddr().String(),
  60. conn: conn,
  61. listener: this,
  62. })
  63. }
  64. }
  65. // @Private
  66. func (this *TCPHub) Recycle(dest string, conn net.Conn) {
  67. if this.accepting {
  68. go this.connCallback(&Connection{
  69. dest: dest,
  70. conn: conn,
  71. listener: this,
  72. })
  73. }
  74. }