connection.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package tcp
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "reflect"
  7. "time"
  8. )
  9. var (
  10. ErrInvalidConn = errors.New("Invalid Connection.")
  11. )
  12. type ConnectionManager interface {
  13. Recycle(string, net.Conn)
  14. }
  15. type RawConnection struct {
  16. net.TCPConn
  17. }
  18. func (this *RawConnection) Reusable() bool {
  19. return false
  20. }
  21. func (this *RawConnection) SetReusable(b bool) {}
  22. type Connection struct {
  23. dest string
  24. conn net.Conn
  25. listener ConnectionManager
  26. reusable bool
  27. }
  28. func NewConnection(dest string, conn net.Conn, manager ConnectionManager) *Connection {
  29. return &Connection{
  30. dest: dest,
  31. conn: conn,
  32. listener: manager,
  33. reusable: effectiveConfig.ConnectionReuse,
  34. }
  35. }
  36. func (this *Connection) Read(b []byte) (int, error) {
  37. if this == nil || this.conn == nil {
  38. return 0, io.EOF
  39. }
  40. return this.conn.Read(b)
  41. }
  42. func (this *Connection) Write(b []byte) (int, error) {
  43. if this == nil || this.conn == nil {
  44. return 0, io.ErrClosedPipe
  45. }
  46. return this.conn.Write(b)
  47. }
  48. func (this *Connection) Close() error {
  49. if this == nil || this.conn == nil {
  50. return io.ErrClosedPipe
  51. }
  52. if this.Reusable() {
  53. this.listener.Recycle(this.dest, this.conn)
  54. return nil
  55. }
  56. err := this.conn.Close()
  57. this.conn = nil
  58. return err
  59. }
  60. func (this *Connection) LocalAddr() net.Addr {
  61. return this.conn.LocalAddr()
  62. }
  63. func (this *Connection) RemoteAddr() net.Addr {
  64. return this.conn.RemoteAddr()
  65. }
  66. func (this *Connection) SetDeadline(t time.Time) error {
  67. return this.conn.SetDeadline(t)
  68. }
  69. func (this *Connection) SetReadDeadline(t time.Time) error {
  70. return this.conn.SetReadDeadline(t)
  71. }
  72. func (this *Connection) SetWriteDeadline(t time.Time) error {
  73. return this.conn.SetWriteDeadline(t)
  74. }
  75. func (this *Connection) SetReusable(reusable bool) {
  76. if !effectiveConfig.ConnectionReuse {
  77. return
  78. }
  79. this.reusable = reusable
  80. }
  81. func (this *Connection) Reusable() bool {
  82. return this.reusable
  83. }
  84. func (this *Connection) SysFd() (int, error) {
  85. cv := reflect.ValueOf(this.conn)
  86. switch ce := cv.Elem(); ce.Kind() {
  87. case reflect.Struct:
  88. netfd := ce.FieldByName("conn").FieldByName("fd")
  89. switch fe := netfd.Elem(); fe.Kind() {
  90. case reflect.Struct:
  91. fd := fe.FieldByName("sysfd")
  92. return int(fd.Int()), nil
  93. }
  94. }
  95. return 0, ErrInvalidConn
  96. }