connector.go
1.89 KB
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
92
93
94
95
96
97
98
99
100
package components
import (
"fmt"
"net"
"pro2d/common/logger"
)
type ConnectorOption func(*Connector)
func WithCtorSplitter(splitter ISplitter) ConnectorOption {
return func(connector *Connector) {
connector.splitter = splitter
}
}
func WithCtorCount(count int) ConnectorOption {
return func(connector *Connector) {
connector.sum = count
}
}
type Connector struct {
IConnector
IServer
splitter ISplitter
ip string
port int
sum int
Conns IConnManage
ids uint32
}
func NewConnector(ip string, port int, options ...ConnectorOption) IConnector {
c := &Connector{
ids: 0,
ip: ip,
port: port,
Conns: NewConnManage(),
}
for _, option := range options {
option(c)
}
return c
}
func (c *Connector) Connect() error {
if c.sum == 0 {
c.sum = 1
}
for i := 0; i < c.sum; i++ {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", c.ip, c.port))
if err != nil {
return err
}
c.ids++
cli := NewConn(int(c.ids), conn, c.splitter)
cli.SetConnectionCallback(c.OnConnect)
cli.SetMessageCallback(c.OnMessage)
cli.SetCloseCallback(c.OnClose)
cli.SetTimerCallback(c.OnTimer)
cli.Start()
}
return nil
}
func (c *Connector) DisConnect() {
c.Conns.StopAllConns()
}
func (c *Connector) Send(cmd uint32, b []byte) {
c.Conns.Range(func(key interface{}, value interface{}) bool {
conn := value.(IConnection)
conn.Send(0, cmd, b)
return true
})
}
func (c *Connector) GetSplitter() ISplitter {
return c.splitter
}
func (c *Connector) OnConnect(conn IConnection) {
c.Conns.AddConn(conn.GetID(), conn)
}
func (c *Connector) OnMessage(msg IMessage) {
logger.Debug("recv msg cmd: %d, conn: %d data: %s", msg.GetHeader().GetMsgID(), msg.GetSID(), msg.GetData())
}
func (c *Connector) OnClose(conn IConnection) {
logger.Debug("onclose id: %d", conn.GetID())
}
func (c *Connector) OnTimer(conn IConnection) {
logger.Debug("ontimer id: %d", conn.GetID())
}