-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
74 lines (64 loc) · 1.33 KB
/
tcp.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
package hub
import (
"crypto/tls"
"errors"
"net"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
ErrorClosedConnection = errors.New("Connection already closed.")
)
type TCPHub struct {
listener net.Listener
connCallback ConnectionHandler
accepting bool
}
func ListenTCP(port v2net.Port, callback ConnectionHandler, tlsConfig *tls.Config) (*TCPHub, error) {
listener, err := net.ListenTCP("tcp", &net.TCPAddr{
IP: []byte{0, 0, 0, 0},
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
}
func (this *TCPHub) Close() {
this.accepting = false
this.listener.Close()
this.listener = nil
}
func (this *TCPHub) start() {
this.accepting = true
for this.accepting {
conn, err := this.listener.Accept()
if err != nil {
if this.accepting {
log.Warning("Listener: Failed to accept new TCP connection: ", err)
}
continue
}
go this.connCallback(&Connection{
conn: conn,
listener: this,
})
}
}
func (this *TCPHub) recycle(conn *net.TCPConn) {
}