2015-09-24 12:51:19 +00:00
|
|
|
package net
|
|
|
|
|
|
|
|
import (
|
2015-10-31 13:08:13 +00:00
|
|
|
"io"
|
2015-09-24 12:51:19 +00:00
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
emptyTime time.Time
|
|
|
|
)
|
|
|
|
|
|
|
|
type TimeOutReader struct {
|
2015-10-31 13:08:13 +00:00
|
|
|
timeout int
|
2015-09-24 12:51:19 +00:00
|
|
|
connection net.Conn
|
2015-10-31 13:08:13 +00:00
|
|
|
worker io.Reader
|
2015-09-24 12:51:19 +00:00
|
|
|
}
|
|
|
|
|
2016-02-01 11:38:38 +00:00
|
|
|
func NewTimeOutReader(timeout int /* seconds */, connection net.Conn) *TimeOutReader {
|
2015-10-31 08:39:45 +00:00
|
|
|
reader := &TimeOutReader{
|
2015-09-24 12:51:19 +00:00
|
|
|
connection: connection,
|
2016-01-04 21:57:17 +00:00
|
|
|
timeout: -100,
|
2015-09-24 12:51:19 +00:00
|
|
|
}
|
2015-10-31 13:08:13 +00:00
|
|
|
reader.SetTimeOut(timeout)
|
|
|
|
return reader
|
2015-09-24 12:51:19 +00:00
|
|
|
}
|
|
|
|
|
2015-10-31 08:39:45 +00:00
|
|
|
func (reader *TimeOutReader) Read(p []byte) (int, error) {
|
|
|
|
return reader.worker.Read(p)
|
2015-09-24 12:51:19 +00:00
|
|
|
}
|
2015-10-03 22:21:06 +00:00
|
|
|
|
|
|
|
func (reader *TimeOutReader) GetTimeOut() int {
|
|
|
|
return reader.timeout
|
|
|
|
}
|
|
|
|
|
|
|
|
func (reader *TimeOutReader) SetTimeOut(value int) {
|
2016-01-04 21:01:46 +00:00
|
|
|
if value == reader.timeout {
|
|
|
|
return
|
|
|
|
}
|
2015-10-31 13:08:13 +00:00
|
|
|
reader.timeout = value
|
|
|
|
if value > 0 {
|
|
|
|
reader.worker = &timedReaderWorker{
|
|
|
|
timeout: value,
|
|
|
|
connection: reader.connection,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
reader.worker = &noOpReaderWorker{
|
|
|
|
connection: reader.connection,
|
|
|
|
}
|
|
|
|
}
|
2015-10-31 08:39:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type timedReaderWorker struct {
|
2015-10-31 13:08:13 +00:00
|
|
|
timeout int
|
|
|
|
connection net.Conn
|
2015-10-31 08:39:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (this *timedReaderWorker) Read(p []byte) (int, error) {
|
2015-10-31 13:08:13 +00:00
|
|
|
deadline := time.Duration(this.timeout) * time.Second
|
2015-10-31 08:39:45 +00:00
|
|
|
this.connection.SetReadDeadline(time.Now().Add(deadline))
|
2015-10-31 13:08:13 +00:00
|
|
|
nBytes, err := this.connection.Read(p)
|
|
|
|
this.connection.SetReadDeadline(emptyTime)
|
|
|
|
return nBytes, err
|
2015-10-31 08:39:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type noOpReaderWorker struct {
|
2015-10-31 13:08:13 +00:00
|
|
|
connection net.Conn
|
2015-10-31 08:39:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (this *noOpReaderWorker) Read(p []byte) (int, error) {
|
2015-10-31 13:08:13 +00:00
|
|
|
return this.connection.Read(p)
|
2015-10-03 22:21:06 +00:00
|
|
|
}
|