connection.go 1.8 KB

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