tcp.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package hub
  2. import (
  3. "errors"
  4. "net"
  5. "github.com/v2ray/v2ray-core/common/log"
  6. v2net "github.com/v2ray/v2ray-core/common/net"
  7. )
  8. var (
  9. ErrorClosedConnection = errors.New("Connection already closed.")
  10. )
  11. type TCPHub struct {
  12. listener *net.TCPListener
  13. connCallback ConnectionHandler
  14. accepting bool
  15. }
  16. func ListenTCP(port v2net.Port, callback ConnectionHandler) (*TCPHub, error) {
  17. listener, err := net.ListenTCP("tcp", &net.TCPAddr{
  18. IP: []byte{0, 0, 0, 0},
  19. Port: int(port),
  20. Zone: "",
  21. })
  22. if err != nil {
  23. return nil, err
  24. }
  25. tcpListener := &TCPHub{
  26. listener: listener,
  27. connCallback: callback,
  28. }
  29. go tcpListener.start()
  30. return tcpListener, nil
  31. }
  32. func (this *TCPHub) Close() {
  33. this.accepting = false
  34. this.listener.Close()
  35. this.listener = nil
  36. }
  37. func (this *TCPHub) start() {
  38. this.accepting = true
  39. for this.accepting {
  40. conn, err := this.listener.AcceptTCP()
  41. if err != nil {
  42. if this.accepting {
  43. log.Warning("Listener: Failed to accept new TCP connection: ", err)
  44. }
  45. continue
  46. }
  47. go this.connCallback(&TCPConnection{
  48. conn: conn,
  49. listener: this,
  50. })
  51. }
  52. }
  53. func (this *TCPHub) recycle(conn *net.TCPConn) {
  54. }