connection.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package hub
  2. import (
  3. "net"
  4. "time"
  5. "github.com/v2ray/v2ray-core/common"
  6. )
  7. type ConnectionHandler func(Connection)
  8. type Connection interface {
  9. common.Releasable
  10. Read([]byte) (int, error)
  11. Write([]byte) (int, error)
  12. Close() error
  13. LocalAddr() net.Addr
  14. RemoteAddr() net.Addr
  15. SetDeadline(t time.Time) error
  16. SetReadDeadline(t time.Time) error
  17. SetWriteDeadline(t time.Time) error
  18. CloseRead() error
  19. CloseWrite() error
  20. }
  21. type TCPConnection struct {
  22. conn *net.TCPConn
  23. listener *TCPHub
  24. }
  25. func (this *TCPConnection) Read(b []byte) (int, error) {
  26. if this == nil || this.conn == nil {
  27. return 0, ErrorClosedConnection
  28. }
  29. return this.conn.Read(b)
  30. }
  31. func (this *TCPConnection) Write(b []byte) (int, error) {
  32. if this == nil || this.conn == nil {
  33. return 0, ErrorClosedConnection
  34. }
  35. return this.conn.Write(b)
  36. }
  37. func (this *TCPConnection) Close() error {
  38. if this == nil || this.conn == nil {
  39. return ErrorClosedConnection
  40. }
  41. err := this.conn.Close()
  42. return err
  43. }
  44. func (this *TCPConnection) Release() {
  45. if this == nil || this.listener == nil {
  46. return
  47. }
  48. this.Close()
  49. this.conn = nil
  50. this.listener = nil
  51. }
  52. func (this *TCPConnection) LocalAddr() net.Addr {
  53. return this.conn.LocalAddr()
  54. }
  55. func (this *TCPConnection) RemoteAddr() net.Addr {
  56. return this.conn.RemoteAddr()
  57. }
  58. func (this *TCPConnection) SetDeadline(t time.Time) error {
  59. return this.conn.SetDeadline(t)
  60. }
  61. func (this *TCPConnection) SetReadDeadline(t time.Time) error {
  62. return this.conn.SetReadDeadline(t)
  63. }
  64. func (this *TCPConnection) SetWriteDeadline(t time.Time) error {
  65. return this.conn.SetWriteDeadline(t)
  66. }
  67. func (this *TCPConnection) CloseRead() error {
  68. if this == nil || this.conn == nil {
  69. return nil
  70. }
  71. return this.conn.CloseRead()
  72. }
  73. func (this *TCPConnection) CloseWrite() error {
  74. if this == nil || this.conn == nil {
  75. return nil
  76. }
  77. return this.conn.CloseWrite()
  78. }