2016-03-12 11:52:13 +03:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const defaultBufSize = 4096
|
|
|
|
|
2016-03-12 13:41:02 +03:00
|
|
|
var noDeadline = time.Time{}
|
2016-03-12 11:52:13 +03:00
|
|
|
|
|
|
|
type Conn struct {
|
2016-03-12 13:41:02 +03:00
|
|
|
idx int
|
|
|
|
|
|
|
|
netConn net.Conn
|
2016-03-12 11:52:13 +03:00
|
|
|
Rd *bufio.Reader
|
|
|
|
Buf []byte
|
|
|
|
|
|
|
|
UsedAt time.Time
|
|
|
|
ReadTimeout time.Duration
|
|
|
|
WriteTimeout time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConn(netConn net.Conn) *Conn {
|
|
|
|
cn := &Conn{
|
2016-03-12 13:41:02 +03:00
|
|
|
idx: -1,
|
|
|
|
|
|
|
|
netConn: netConn,
|
2016-03-12 11:52:13 +03:00
|
|
|
Buf: make([]byte, defaultBufSize),
|
|
|
|
|
|
|
|
UsedAt: time.Now(),
|
|
|
|
}
|
|
|
|
cn.Rd = bufio.NewReader(cn)
|
|
|
|
return cn
|
|
|
|
}
|
|
|
|
|
2016-03-12 13:41:02 +03:00
|
|
|
func (cn *Conn) SetNetConn(netConn net.Conn) {
|
|
|
|
cn.netConn = netConn
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
}
|
|
|
|
|
2016-03-12 11:52:13 +03:00
|
|
|
func (cn *Conn) Read(b []byte) (int, error) {
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
if cn.ReadTimeout != 0 {
|
2016-03-12 13:41:02 +03:00
|
|
|
cn.netConn.SetReadDeadline(cn.UsedAt.Add(cn.ReadTimeout))
|
2016-03-12 11:52:13 +03:00
|
|
|
} else {
|
2016-03-12 13:41:02 +03:00
|
|
|
cn.netConn.SetReadDeadline(noDeadline)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
2016-03-12 13:41:02 +03:00
|
|
|
return cn.netConn.Read(b)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) Write(b []byte) (int, error) {
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
if cn.WriteTimeout != 0 {
|
2016-03-12 13:41:02 +03:00
|
|
|
cn.netConn.SetWriteDeadline(cn.UsedAt.Add(cn.WriteTimeout))
|
2016-03-12 11:52:13 +03:00
|
|
|
} else {
|
2016-03-12 13:41:02 +03:00
|
|
|
cn.netConn.SetWriteDeadline(noDeadline)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
2016-03-12 13:41:02 +03:00
|
|
|
return cn.netConn.Write(b)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) RemoteAddr() net.Addr {
|
2016-03-12 13:41:02 +03:00
|
|
|
return cn.netConn.RemoteAddr()
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) Close() error {
|
2016-03-12 13:41:02 +03:00
|
|
|
return cn.netConn.Close()
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|