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.

81 lines
1.5 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. }
  34. func (c *Conn) Read(b []byte) (count int, e error) {
  35. err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
  36. if err != nil {
  37. return 0, err
  38. }
  39. count, e = c.Conn.Read(b)
  40. if e == nil {
  41. stats.BytesIn(int64(count))
  42. }
  43. return
  44. }
  45. func (c *Conn) Write(b []byte) (count int, e error) {
  46. err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
  47. if err != nil {
  48. return 0, err
  49. }
  50. count, e = c.Conn.Write(b)
  51. if e == nil {
  52. stats.BytesOut(int64(count))
  53. }
  54. return
  55. }
  56. func (c *Conn) Close() error {
  57. stats.ConnectionClose()
  58. return c.Conn.Close()
  59. }
  60. func NewListener(addr string, timeout time.Duration) (net.Listener, error) {
  61. l, err := net.Listen("tcp", addr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. tl := &Listener{
  66. Listener: l,
  67. ReadTimeout: timeout,
  68. WriteTimeout: timeout,
  69. }
  70. return tl, nil
  71. }