reusable connection

pull/168/head
v2ray 2016-05-29 22:33:04 +02:00
parent 9b07ffd68f
commit da24d00367
2 changed files with 34 additions and 4 deletions

View File

@ -10,6 +10,7 @@ type ConnectionHandler func(*Connection)
type Connection struct { type Connection struct {
conn net.Conn conn net.Conn
listener *TCPHub listener *TCPHub
reusable bool
} }
func (this *Connection) Read(b []byte) (int, error) { func (this *Connection) Read(b []byte) (int, error) {
@ -31,8 +32,11 @@ func (this *Connection) Close() error {
if this == nil || this.conn == nil { if this == nil || this.conn == nil {
return ErrorClosedConnection return ErrorClosedConnection
} }
err := this.conn.Close() if this.Reusable() {
return err this.listener.Recycle(this.conn)
return nil
}
return this.conn.Close()
} }
func (this *Connection) Release() { func (this *Connection) Release() {
@ -64,3 +68,11 @@ func (this *Connection) SetReadDeadline(t time.Time) error {
func (this *Connection) SetWriteDeadline(t time.Time) error { func (this *Connection) SetWriteDeadline(t time.Time) error {
return this.conn.SetWriteDeadline(t) return this.conn.SetWriteDeadline(t)
} }
func (this *Connection) SetReusable(reusable bool) {
this.reusable = reusable
}
func (this *Connection) Reusable() bool {
return this.reusable
}

View File

@ -4,6 +4,7 @@ import (
"crypto/tls" "crypto/tls"
"errors" "errors"
"net" "net"
"sync"
"github.com/v2ray/v2ray-core/common/log" "github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net" v2net "github.com/v2ray/v2ray-core/common/net"
@ -14,6 +15,7 @@ var (
) )
type TCPHub struct { type TCPHub struct {
sync.Mutex
listener net.Listener listener net.Listener
connCallback ConnectionHandler connCallback ConnectionHandler
accepting bool accepting bool
@ -47,6 +49,9 @@ func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandle
} }
func (this *TCPHub) Close() { func (this *TCPHub) Close() {
this.Lock()
defer this.Unlock()
this.accepting = false this.accepting = false
this.listener.Close() this.listener.Close()
this.listener = nil this.listener = nil
@ -55,7 +60,14 @@ func (this *TCPHub) Close() {
func (this *TCPHub) start() { func (this *TCPHub) start() {
this.accepting = true this.accepting = true
for this.accepting { for this.accepting {
this.Lock()
if !this.accepting {
this.Unlock()
break
}
conn, err := this.listener.Accept() conn, err := this.listener.Accept()
this.Unlock()
if err != nil { if err != nil {
if this.accepting { if this.accepting {
log.Warning("Listener: Failed to accept new TCP connection: ", err) log.Warning("Listener: Failed to accept new TCP connection: ", err)
@ -69,6 +81,12 @@ func (this *TCPHub) start() {
} }
} }
func (this *TCPHub) recycle(conn *net.TCPConn) { // @Private
func (this *TCPHub) Recycle(conn net.Conn) {
if this.accepting {
go this.connCallback(&Connection{
conn: conn,
listener: this,
})
}
} }