timed_io.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package net
  2. import (
  3. "io"
  4. "net"
  5. "time"
  6. )
  7. var (
  8. emptyTime time.Time
  9. )
  10. type TimeOutReader struct {
  11. timeout int
  12. connection net.Conn
  13. worker io.Reader
  14. }
  15. func NewTimeOutReader(timeout int, connection net.Conn) *TimeOutReader {
  16. reader := &TimeOutReader{
  17. connection: connection,
  18. }
  19. reader.SetTimeOut(timeout)
  20. return reader
  21. }
  22. func (reader *TimeOutReader) Read(p []byte) (int, error) {
  23. return reader.worker.Read(p)
  24. }
  25. func (reader *TimeOutReader) GetTimeOut() int {
  26. return reader.timeout
  27. }
  28. func (reader *TimeOutReader) SetTimeOut(value int) {
  29. reader.timeout = value
  30. if value > 0 {
  31. reader.worker = &timedReaderWorker{
  32. timeout: value,
  33. connection: reader.connection,
  34. }
  35. } else {
  36. reader.worker = &noOpReaderWorker{
  37. connection: reader.connection,
  38. }
  39. }
  40. }
  41. type timedReaderWorker struct {
  42. timeout int
  43. connection net.Conn
  44. }
  45. func (this *timedReaderWorker) Read(p []byte) (int, error) {
  46. deadline := time.Duration(this.timeout) * time.Second
  47. this.connection.SetReadDeadline(time.Now().Add(deadline))
  48. nBytes, err := this.connection.Read(p)
  49. this.connection.SetReadDeadline(emptyTime)
  50. return nBytes, err
  51. }
  52. type noOpReaderWorker struct {
  53. connection net.Conn
  54. }
  55. func (this *noOpReaderWorker) Read(p []byte) (int, error) {
  56. return this.connection.Read(p)
  57. }