timed_io.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. if value == reader.timeout {
  30. return
  31. }
  32. reader.timeout = value
  33. if value > 0 {
  34. reader.worker = &timedReaderWorker{
  35. timeout: value,
  36. connection: reader.connection,
  37. }
  38. } else {
  39. reader.worker = &noOpReaderWorker{
  40. connection: reader.connection,
  41. }
  42. }
  43. }
  44. type timedReaderWorker struct {
  45. timeout int
  46. connection net.Conn
  47. }
  48. func (this *timedReaderWorker) Read(p []byte) (int, error) {
  49. deadline := time.Duration(this.timeout) * time.Second
  50. this.connection.SetReadDeadline(time.Now().Add(deadline))
  51. nBytes, err := this.connection.Read(p)
  52. this.connection.SetReadDeadline(emptyTime)
  53. return nBytes, err
  54. }
  55. type noOpReaderWorker struct {
  56. connection net.Conn
  57. }
  58. func (this *noOpReaderWorker) Read(p []byte) (int, error) {
  59. return this.connection.Read(p)
  60. }