1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 10:37:09 -05:00
v2fly/transport/internet/tcp_hub.go

82 lines
1.7 KiB
Go
Raw Normal View History

2016-06-14 16:54:08 -04:00
package internet
import (
"errors"
"net"
"sync"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
2016-06-27 02:53:35 -04:00
ErrClosedConnection = errors.New("Connection already closed.")
2016-06-14 16:54:08 -04:00
KCPListenFunc ListenFunc
TCPListenFunc ListenFunc
RawTCPListenFunc ListenFunc
)
type ListenFunc func(address v2net.Address, port v2net.Port) (Listener, error)
type Listener interface {
Accept() (Connection, error)
Close() error
Addr() net.Addr
}
type TCPHub struct {
sync.Mutex
listener Listener
connCallback ConnectionHandler
accepting bool
}
func ListenTCP(address v2net.Address, port v2net.Port, callback ConnectionHandler, settings *StreamSettings) (*TCPHub, error) {
var listener Listener
var err error
2016-06-14 19:08:03 -04:00
switch {
case settings.IsCapableOf(StreamConnectionTypeTCP):
2016-06-14 16:54:08 -04:00
listener, err = TCPListenFunc(address, port)
2016-06-14 19:08:03 -04:00
case settings.IsCapableOf(StreamConnectionTypeKCP):
listener, err = KCPListenFunc(address, port)
case settings.IsCapableOf(StreamConnectionTypeRawTCP):
2016-06-14 16:54:08 -04:00
listener, err = RawTCPListenFunc(address, port)
2016-06-14 19:08:03 -04:00
default:
2016-06-17 12:03:31 -04:00
log.Error("Internet|Listener: Unknown stream type: ", settings.Type)
2016-06-14 19:08:03 -04:00
err = ErrUnsupportedStreamType
2016-06-14 16:54:08 -04:00
}
if err != nil {
2016-06-17 12:03:31 -04:00
log.Warning("Internet|Listener: Failed to listen on ", address, ":", port)
2016-06-14 16:54:08 -04:00
return nil, err
}
hub := &TCPHub{
listener: listener,
connCallback: callback,
}
go hub.start()
return hub, nil
}
func (this *TCPHub) Close() {
this.accepting = false
this.listener.Close()
}
func (this *TCPHub) start() {
this.accepting = true
for this.accepting {
conn, err := this.listener.Accept()
if err != nil {
if this.accepting {
2016-06-17 12:03:31 -04:00
log.Warning("Internet|Listener: Failed to accept new TCP connection: ", err)
2016-06-14 16:54:08 -04:00
}
continue
}
go this.connCallback(conn)
}
}