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

73 lines
1.4 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 {
2016-08-25 15:55:49 -04:00
timeout uint32
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-08-25 15:55:49 -04:00
func NewTimeOutReader(timeout uint32 /* 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-08-25 15:55:49 -04:00
timeout: 0,
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
2016-08-25 15:55:49 -04:00
func (reader *TimeOutReader) GetTimeOut() uint32 {
2015-10-03 18:21:06 -04:00
return reader.timeout
}
2016-08-25 15:55:49 -04:00
func (reader *TimeOutReader) SetTimeOut(value uint32) {
if reader.worker != nil && 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 {
2016-08-25 15:55:49 -04:00
timeout uint32
2015-10-31 09:08:13 -04:00
connection net.Conn
2015-10-31 04:39:45 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *timedReaderWorker) Read(p []byte) (int, error) {
deadline := time.Duration(v.timeout) * time.Second
v.connection.SetReadDeadline(time.Now().Add(deadline))
nBytes, err := v.connection.Read(p)
v.connection.SetReadDeadline(emptyTime)
2015-10-31 09:08:13 -04:00
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
}
2016-11-27 15:39:09 -05:00
func (v *noOpReaderWorker) Read(p []byte) (int, error) {
return v.connection.Read(p)
2015-10-03 18:21:06 -04:00
}