connection.go 2.1 KB

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