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