connection.go 1.5 KB

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