connection.go 1.4 KB

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