connection.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package tcp
  2. import (
  3. "io"
  4. "net"
  5. "time"
  6. "github.com/v2ray/v2ray-core/transport/internet/internal"
  7. )
  8. type ConnectionManager interface {
  9. Recycle(string, net.Conn)
  10. }
  11. type RawConnection struct {
  12. net.TCPConn
  13. }
  14. func (this *RawConnection) Reusable() bool {
  15. return false
  16. }
  17. func (this *RawConnection) SetReusable(b bool) {}
  18. func (this *RawConnection) SysFd() (int, error) {
  19. return internal.GetSysFd(&this.TCPConn)
  20. }
  21. type Connection struct {
  22. dest string
  23. conn net.Conn
  24. listener ConnectionManager
  25. reusable bool
  26. }
  27. func NewConnection(dest string, conn net.Conn, manager ConnectionManager) *Connection {
  28. return &Connection{
  29. dest: dest,
  30. conn: conn,
  31. listener: manager,
  32. reusable: effectiveConfig.ConnectionReuse,
  33. }
  34. }
  35. func (this *Connection) Read(b []byte) (int, error) {
  36. if this == nil || this.conn == nil {
  37. return 0, io.EOF
  38. }
  39. return this.conn.Read(b)
  40. }
  41. func (this *Connection) Write(b []byte) (int, error) {
  42. if this == nil || this.conn == nil {
  43. return 0, io.ErrClosedPipe
  44. }
  45. return this.conn.Write(b)
  46. }
  47. func (this *Connection) Close() error {
  48. if this == nil || this.conn == nil {
  49. return io.ErrClosedPipe
  50. }
  51. if this.Reusable() {
  52. this.listener.Recycle(this.dest, this.conn)
  53. return nil
  54. }
  55. err := this.conn.Close()
  56. this.conn = nil
  57. return err
  58. }
  59. func (this *Connection) LocalAddr() net.Addr {
  60. return this.conn.LocalAddr()
  61. }
  62. func (this *Connection) RemoteAddr() net.Addr {
  63. return this.conn.RemoteAddr()
  64. }
  65. func (this *Connection) SetDeadline(t time.Time) error {
  66. return this.conn.SetDeadline(t)
  67. }
  68. func (this *Connection) SetReadDeadline(t time.Time) error {
  69. return this.conn.SetReadDeadline(t)
  70. }
  71. func (this *Connection) SetWriteDeadline(t time.Time) error {
  72. return this.conn.SetWriteDeadline(t)
  73. }
  74. func (this *Connection) SetReusable(reusable bool) {
  75. if !effectiveConfig.ConnectionReuse {
  76. return
  77. }
  78. this.reusable = reusable
  79. }
  80. func (this *Connection) Reusable() bool {
  81. return this.reusable
  82. }
  83. func (this *Connection) SysFd() (int, error) {
  84. return internal.GetSysFd(this.conn)
  85. }