1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-01 19:45:24 +00:00
v2fly/transport/internet/tcp_hub.go

82 lines
1.7 KiB
Go
Raw Normal View History

2016-06-14 20:54:08 +00:00
package internet
import (
"errors"
"net"
"sync"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
ErrorClosedConnection = errors.New("Connection already closed.")
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 23:08:03 +00:00
switch {
case settings.IsCapableOf(StreamConnectionTypeTCP):
2016-06-14 20:54:08 +00:00
listener, err = TCPListenFunc(address, port)
2016-06-14 23:08:03 +00:00
case settings.IsCapableOf(StreamConnectionTypeKCP):
listener, err = KCPListenFunc(address, port)
case settings.IsCapableOf(StreamConnectionTypeRawTCP):
2016-06-14 20:54:08 +00:00
listener, err = RawTCPListenFunc(address, port)
2016-06-14 23:08:03 +00:00
default:
2016-06-17 16:03:31 +00:00
log.Error("Internet|Listener: Unknown stream type: ", settings.Type)
2016-06-14 23:08:03 +00:00
err = ErrUnsupportedStreamType
2016-06-14 20:54:08 +00:00
}
if err != nil {
2016-06-17 16:03:31 +00:00
log.Warning("Internet|Listener: Failed to listen on ", address, ":", port)
2016-06-14 20:54:08 +00: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 16:03:31 +00:00
log.Warning("Internet|Listener: Failed to accept new TCP connection: ", err)
2016-06-14 20:54:08 +00:00
}
continue
}
go this.connCallback(conn)
}
}