1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-08 06:14:23 -04:00
v2fly/transport/hub/tcp.go

85 lines
1.5 KiB
Go
Raw Normal View History

2016-01-28 11:08:32 -05:00
package hub
import (
"crypto/tls"
"errors"
"net"
2016-05-29 16:33:04 -04:00
"sync"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
ErrorClosedConnection = errors.New("Connection already closed.")
)
2016-01-28 14:47:00 -05:00
type TCPHub struct {
2016-05-29 16:33:04 -04:00
sync.Mutex
listener net.Listener
2016-04-27 17:01:31 -04:00
connCallback ConnectionHandler
accepting bool
}
2016-05-29 10:37:52 -04:00
func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandler, tlsConfig *tls.Config) (*TCPHub, error) {
listener, err := net.ListenTCP("tcp", &net.TCPAddr{
2016-05-29 10:37:52 -04:00
IP: address.IP(),
Port: int(port),
Zone: "",
})
if err != nil {
return nil, err
}
var hub *TCPHub
if tlsConfig != nil {
tlsListener := tls.NewListener(listener, tlsConfig)
hub = &TCPHub{
listener: tlsListener,
connCallback: callback,
}
} else {
hub = &TCPHub{
listener: listener,
connCallback: callback,
}
}
go hub.start()
return hub, nil
}
2016-01-28 14:47:00 -05:00
func (this *TCPHub) Close() {
this.accepting = false
this.listener.Close()
}
2016-01-28 14:47:00 -05:00
func (this *TCPHub) start() {
this.accepting = true
for this.accepting {
conn, err := this.listener.Accept()
2016-05-29 16:33:04 -04:00
if err != nil {
if this.accepting {
log.Warning("Listener: Failed to accept new TCP connection: ", err)
}
continue
}
2016-05-02 17:53:16 -04:00
go this.connCallback(&Connection{
2016-05-30 18:21:41 -04:00
dest: conn.RemoteAddr().String(),
conn: conn,
listener: this,
})
}
}
2016-05-29 16:33:04 -04:00
// @Private
2016-05-30 18:21:41 -04:00
func (this *TCPHub) Recycle(dest string, conn net.Conn) {
2016-05-29 16:33:04 -04:00
if this.accepting {
go this.connCallback(&Connection{
2016-05-30 18:21:41 -04:00
dest: dest,
2016-05-29 16:33:04 -04:00
conn: conn,
listener: this,
})
}
}