connection.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package hub
  2. import (
  3. "errors"
  4. "net"
  5. "reflect"
  6. "time"
  7. "github.com/v2ray/v2ray-core/transport"
  8. )
  9. var (
  10. ErrInvalidConn = errors.New("Invalid Connection.")
  11. )
  12. type ConnectionHandler func(*Connection)
  13. type ConnectionManager interface {
  14. Recycle(string, net.Conn)
  15. }
  16. type Connection struct {
  17. dest string
  18. conn net.Conn
  19. listener ConnectionManager
  20. reusable bool
  21. }
  22. func (this *Connection) Read(b []byte) (int, error) {
  23. if this == nil || this.conn == nil {
  24. return 0, ErrorClosedConnection
  25. }
  26. return this.conn.Read(b)
  27. }
  28. func (this *Connection) Write(b []byte) (int, error) {
  29. if this == nil || this.conn == nil {
  30. return 0, ErrorClosedConnection
  31. }
  32. return this.conn.Write(b)
  33. }
  34. func (this *Connection) Close() error {
  35. if this == nil || this.conn == nil {
  36. return ErrorClosedConnection
  37. }
  38. if transport.IsConnectionReusable() && this.Reusable() {
  39. this.listener.Recycle(this.dest, this.conn)
  40. return nil
  41. }
  42. return this.conn.Close()
  43. }
  44. func (this *Connection) LocalAddr() net.Addr {
  45. return this.conn.LocalAddr()
  46. }
  47. func (this *Connection) RemoteAddr() net.Addr {
  48. return this.conn.RemoteAddr()
  49. }
  50. func (this *Connection) SetDeadline(t time.Time) error {
  51. return this.conn.SetDeadline(t)
  52. }
  53. func (this *Connection) SetReadDeadline(t time.Time) error {
  54. return this.conn.SetReadDeadline(t)
  55. }
  56. func (this *Connection) SetWriteDeadline(t time.Time) error {
  57. return this.conn.SetWriteDeadline(t)
  58. }
  59. func (this *Connection) SetReusable(reusable bool) {
  60. this.reusable = reusable
  61. }
  62. func (this *Connection) Reusable() bool {
  63. return this.reusable
  64. }
  65. func (this *Connection) SysFd() (int, error) {
  66. cv := reflect.ValueOf(this.conn)
  67. switch ce := cv.Elem(); ce.Kind() {
  68. case reflect.Struct:
  69. netfd := ce.FieldByName("conn").FieldByName("fd")
  70. switch fe := netfd.Elem(); fe.Kind() {
  71. case reflect.Struct:
  72. fd := fe.FieldByName("sysfd")
  73. return int(fd.Int()), nil
  74. }
  75. }
  76. return 0, ErrInvalidConn
  77. }