forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_hub.go
91 lines (77 loc) · 1.91 KB
/
tcp_hub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package internet
import (
"errors"
"net"
"sync"
"v2ray.com/core/common/log"
v2net "v2ray.com/core/common/net"
)
var (
ErrClosedConnection = errors.New("Connection already closed.")
KCPListenFunc ListenFunc
TCPListenFunc ListenFunc
RawTCPListenFunc ListenFunc
WSListenFunc ListenFunc
)
type ListenFunc func(address v2net.Address, port v2net.Port, options ListenOptions) (Listener, error)
type ListenOptions struct {
Stream *StreamConfig
}
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 *StreamConfig) (*TCPHub, error) {
var listener Listener
var err error
options := ListenOptions{
Stream: settings,
}
switch settings.Network {
case v2net.Network_TCP:
listener, err = TCPListenFunc(address, port, options)
case v2net.Network_KCP:
listener, err = KCPListenFunc(address, port, options)
case v2net.Network_WebSocket:
listener, err = WSListenFunc(address, port, options)
case v2net.Network_RawTCP:
listener, err = RawTCPListenFunc(address, port, options)
default:
log.Error("Internet|Listener: Unknown stream type: ", settings.Network)
err = ErrUnsupportedStreamType
}
if err != nil {
log.Warning("Internet|Listener: Failed to listen on ", address, ":", port)
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 {
log.Warning("Internet|Listener: Failed to accept new TCP connection: ", err)
}
continue
}
go this.connCallback(conn)
}
}