1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/common/net/timed_io.go

73 lines
1.3 KiB
Go
Raw Normal View History

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
}
func NewTimeOutReader(timeout int, 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) {
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
}
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
}