timed_io.go 565 B

123456789101112131415161718192021222324252627282930
  1. package net
  2. import (
  3. "net"
  4. "time"
  5. )
  6. var (
  7. emptyTime time.Time
  8. )
  9. type TimeOutReader struct {
  10. timeout int
  11. connection net.Conn
  12. }
  13. func NewTimeOutReader(timeout int, connection net.Conn) *TimeOutReader {
  14. return &TimeOutReader{
  15. timeout: timeout,
  16. connection: connection,
  17. }
  18. }
  19. func (reader *TimeOutReader) Read(p []byte) (n int, err error) {
  20. deadline := time.Duration(reader.timeout) * time.Second
  21. reader.connection.SetReadDeadline(time.Now().Add(deadline))
  22. n, err = reader.connection.Read(p)
  23. reader.connection.SetReadDeadline(emptyTime)
  24. return
  25. }