tcp.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package hub
  2. import (
  3. "net"
  4. "time"
  5. "github.com/v2ray/v2ray-core/common/log"
  6. v2net "github.com/v2ray/v2ray-core/common/net"
  7. )
  8. type TCPConn struct {
  9. conn *net.TCPConn
  10. listener *TCPHub
  11. dirty bool
  12. }
  13. func (this *TCPConn) Read(b []byte) (int, error) {
  14. return this.conn.Read(b)
  15. }
  16. func (this *TCPConn) Write(b []byte) (int, error) {
  17. return this.conn.Write(b)
  18. }
  19. func (this *TCPConn) Close() error {
  20. return this.conn.Close()
  21. }
  22. func (this *TCPConn) Release() {
  23. if this.dirty {
  24. this.Close()
  25. return
  26. }
  27. this.listener.recycle(this.conn)
  28. }
  29. func (this *TCPConn) LocalAddr() net.Addr {
  30. return this.conn.LocalAddr()
  31. }
  32. func (this *TCPConn) RemoteAddr() net.Addr {
  33. return this.conn.RemoteAddr()
  34. }
  35. func (this *TCPConn) SetDeadline(t time.Time) error {
  36. return this.conn.SetDeadline(t)
  37. }
  38. func (this *TCPConn) SetReadDeadline(t time.Time) error {
  39. return this.conn.SetReadDeadline(t)
  40. }
  41. func (this *TCPConn) SetWriteDeadline(t time.Time) error {
  42. return this.conn.SetWriteDeadline(t)
  43. }
  44. func (this *TCPConn) CloseRead() error {
  45. return this.conn.CloseRead()
  46. }
  47. func (this *TCPConn) CloseWrite() error {
  48. return this.conn.CloseWrite()
  49. }
  50. type TCPHub struct {
  51. listener *net.TCPListener
  52. connCallback func(*TCPConn)
  53. accepting bool
  54. }
  55. func ListenTCP(port v2net.Port, callback func(*TCPConn)) (*TCPHub, error) {
  56. listener, err := net.ListenTCP("tcp", &net.TCPAddr{
  57. IP: []byte{0, 0, 0, 0},
  58. Port: int(port),
  59. Zone: "",
  60. })
  61. if err != nil {
  62. return nil, err
  63. }
  64. tcpListener := &TCPHub{
  65. listener: listener,
  66. connCallback: callback,
  67. }
  68. go tcpListener.start()
  69. return tcpListener, nil
  70. }
  71. func (this *TCPHub) Close() {
  72. this.accepting = false
  73. this.listener.Close()
  74. }
  75. func (this *TCPHub) start() {
  76. this.accepting = true
  77. for this.accepting {
  78. conn, err := this.listener.AcceptTCP()
  79. if err != nil {
  80. log.Warning("Listener: Failed to accept new TCP connection: ", err)
  81. continue
  82. }
  83. go this.connCallback(&TCPConn{
  84. conn: conn,
  85. listener: this,
  86. })
  87. }
  88. }
  89. func (this *TCPHub) recycle(conn *net.TCPConn) {
  90. }