You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
1.7 KiB

  1. package util
  2. import (
  3. "net"
  4. "time"
  5. "github.com/chrislusf/seaweedfs/weed/stats"
  6. )
  7. // Listener wraps a net.Listener, and gives a place to store the timeout
  8. // parameters. On Accept, it will wrap the net.Conn with our own Conn for us.
  9. type Listener struct {
  10. net.Listener
  11. ReadTimeout time.Duration
  12. WriteTimeout time.Duration
  13. }
  14. func (l *Listener) Accept() (net.Conn, error) {
  15. c, err := l.Listener.Accept()
  16. if err != nil {
  17. return nil, err
  18. }
  19. stats.ConnectionOpen()
  20. tc := &Conn{
  21. Conn: c,
  22. ReadTimeout: l.ReadTimeout,
  23. WriteTimeout: l.WriteTimeout,
  24. }
  25. return tc, nil
  26. }
  27. // Conn wraps a net.Conn, and sets a deadline for every read
  28. // and write operation.
  29. type Conn struct {
  30. net.Conn
  31. ReadTimeout time.Duration
  32. WriteTimeout time.Duration
  33. isClosed bool
  34. }
  35. func (c *Conn) Read(b []byte) (count int, e error) {
  36. if c.ReadTimeout != 0 {
  37. err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
  38. if err != nil {
  39. return 0, err
  40. }
  41. }
  42. count, e = c.Conn.Read(b)
  43. if e == nil {
  44. stats.BytesIn(int64(count))
  45. }
  46. return
  47. }
  48. func (c *Conn) Write(b []byte) (count int, e error) {
  49. if c.WriteTimeout != 0 {
  50. err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
  51. if err != nil {
  52. return 0, err
  53. }
  54. }
  55. count, e = c.Conn.Write(b)
  56. if e == nil {
  57. stats.BytesOut(int64(count))
  58. }
  59. return
  60. }
  61. func (c *Conn) Close() error {
  62. err := c.Conn.Close()
  63. if err == nil {
  64. if !c.isClosed {
  65. stats.ConnectionClose()
  66. c.isClosed = true
  67. }
  68. }
  69. return err
  70. }
  71. func NewListener(addr string, timeout time.Duration) (net.Listener, error) {
  72. l, err := net.Listen("tcp", addr)
  73. if err != nil {
  74. return nil, err
  75. }
  76. tl := &Listener{
  77. Listener: l,
  78. ReadTimeout: timeout,
  79. WriteTimeout: timeout,
  80. }
  81. return tl, nil
  82. }