-
Notifications
You must be signed in to change notification settings - Fork 55
/
tcp_connector.go
78 lines (62 loc) · 1.33 KB
/
tcp_connector.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
package cherryConnector
import (
cfacade "github.com/cherry-game/cherry/facade"
clog "github.com/cherry-game/cherry/logger"
)
type (
TCPConnector struct {
cfacade.Component
Connector
Options
}
)
func (*TCPConnector) Name() string {
return "tcp_connector"
}
func (t *TCPConnector) OnAfterInit() {
go t.Start()
}
func (t *TCPConnector) OnStop() {
t.Stop()
}
func NewTCP(address string, opts ...Option) *TCPConnector {
if address == "" {
clog.Warn("Create tcp connector fail. Address is null.")
return nil
}
tcp := &TCPConnector{
Options: Options{
address: address,
certFile: "",
keyFile: "",
chanSize: 256,
},
}
for _, opt := range opts {
opt(&tcp.Options)
}
tcp.Connector = NewConnector(tcp.chanSize)
return tcp
}
func (t *TCPConnector) Start() {
listener, err := t.GetListener(t.certFile, t.keyFile, t.address)
if err != nil {
clog.Fatalf("failed to listen: %s", err)
}
clog.Infof("Tcp connector listening at Address %s", t.address)
if t.certFile != "" || t.keyFile != "" {
clog.Infof("certFile = %s, keyFile = %s", t.certFile, t.keyFile)
}
t.Connector.Start()
for t.Running() {
conn, err := listener.Accept()
if err != nil {
clog.Errorf("Failed to accept TCP connection: %s", err.Error())
continue
}
t.InChan(conn)
}
}
func (t *TCPConnector) Stop() {
t.Connector.Stop()
}