connection.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package tcp
  2. import (
  3. "io"
  4. "net"
  5. "time"
  6. "v2ray.com/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. config *Config
  27. }
  28. func NewConnection(dest string, conn net.Conn, manager ConnectionManager, config *Config) *Connection {
  29. return &Connection{
  30. dest: dest,
  31. conn: conn,
  32. listener: manager,
  33. reusable: config.ConnectionReuse,
  34. config: config,
  35. }
  36. }
  37. func (this *Connection) Read(b []byte) (int, error) {
  38. if this == nil || this.conn == nil {
  39. return 0, io.EOF
  40. }
  41. return this.conn.Read(b)
  42. }
  43. func (this *Connection) Write(b []byte) (int, error) {
  44. if this == nil || this.conn == nil {
  45. return 0, io.ErrClosedPipe
  46. }
  47. return this.conn.Write(b)
  48. }
  49. func (this *Connection) Close() error {
  50. if this == nil || this.conn == nil {
  51. return io.ErrClosedPipe
  52. }
  53. if this.Reusable() {
  54. this.listener.Recycle(this.dest, this.conn)
  55. return nil
  56. }
  57. err := this.conn.Close()
  58. this.conn = nil
  59. return err
  60. }
  61. func (this *Connection) LocalAddr() net.Addr {
  62. return this.conn.LocalAddr()
  63. }
  64. func (this *Connection) RemoteAddr() net.Addr {
  65. return this.conn.RemoteAddr()
  66. }
  67. func (this *Connection) SetDeadline(t time.Time) error {
  68. return this.conn.SetDeadline(t)
  69. }
  70. func (this *Connection) SetReadDeadline(t time.Time) error {
  71. return this.conn.SetReadDeadline(t)
  72. }
  73. func (this *Connection) SetWriteDeadline(t time.Time) error {
  74. return this.conn.SetWriteDeadline(t)
  75. }
  76. func (this *Connection) SetReusable(reusable bool) {
  77. if !this.config.ConnectionReuse {
  78. return
  79. }
  80. this.reusable = reusable
  81. }
  82. func (this *Connection) Reusable() bool {
  83. return this.reusable
  84. }
  85. func (this *Connection) SysFd() (int, error) {
  86. return internal.GetSysFd(this.conn)
  87. }