connection.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package hub
  2. import (
  3. "net"
  4. "time"
  5. )
  6. type ConnectionHandler func(*Connection)
  7. type ConnectionManager interface {
  8. Recycle(string, net.Conn)
  9. }
  10. type Connection struct {
  11. dest string
  12. conn net.Conn
  13. listener ConnectionManager
  14. reusable bool
  15. }
  16. func (this *Connection) Read(b []byte) (int, error) {
  17. if this == nil || this.conn == nil {
  18. return 0, ErrorClosedConnection
  19. }
  20. return this.conn.Read(b)
  21. }
  22. func (this *Connection) Write(b []byte) (int, error) {
  23. if this == nil || this.conn == nil {
  24. return 0, ErrorClosedConnection
  25. }
  26. return this.conn.Write(b)
  27. }
  28. func (this *Connection) Close() error {
  29. if this == nil || this.conn == nil {
  30. return ErrorClosedConnection
  31. }
  32. if this.Reusable() {
  33. this.listener.Recycle(this.dest, this.conn)
  34. return nil
  35. }
  36. return this.conn.Close()
  37. }
  38. func (this *Connection) LocalAddr() net.Addr {
  39. return this.conn.LocalAddr()
  40. }
  41. func (this *Connection) RemoteAddr() net.Addr {
  42. return this.conn.RemoteAddr()
  43. }
  44. func (this *Connection) SetDeadline(t time.Time) error {
  45. return this.conn.SetDeadline(t)
  46. }
  47. func (this *Connection) SetReadDeadline(t time.Time) error {
  48. return this.conn.SetReadDeadline(t)
  49. }
  50. func (this *Connection) SetWriteDeadline(t time.Time) error {
  51. return this.conn.SetWriteDeadline(t)
  52. }
  53. func (this *Connection) SetReusable(reusable bool) {
  54. this.reusable = reusable
  55. }
  56. func (this *Connection) Reusable() bool {
  57. return this.reusable
  58. }