connector.go
2.03 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"
"github.com/golang/protobuf/proto"
"net"
"pro2d/common/logger"
"pro2d/pb"
)
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
IConnection
IServer
Id int
splitter ISplitter
ip string
port int
sum int
}
func NewConnector(ip string, port int, options ...ConnectorOption) IConnector {
c := &Connector{
ip: ip,
port: port,
}
for _, option := range options {
option(c)
}
return c
}
func (c *Connector) GetConn() IConnection {
return c.IConnection
}
func (c *Connector) Connect() error {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", c.ip, c.port))
if err != nil {
return err
}
cli := NewConn(c.Id, conn, c.splitter)
cli.SetMessageCallback(c.OnMessage)
cli.SetCloseCallback(c.OnClose)
cli.SetTimerCallback(c.OnTimer)
c.IConnection = cli
return nil
}
func (c *Connector) DisConnect() {
c.IConnection.Stop()
}
func (c *Connector) Send(cmd uint32, b []byte, preserve uint32) error {
logger.Debug("connector send cmd: %d, msg: %s", cmd, b)
return c.IConnection.Send(0, cmd, b, preserve)
}
func (c *Connector) SendPB(cmd pb.ProtoCode, b proto.Message, preserve uint32) error {
if b == nil {
return c.Send(uint32(cmd), nil, preserve)
}
l, err := proto.Marshal(b)
if err != nil {
return err
}
return c.Send(uint32(cmd), l, preserve)
}
func (c *Connector) GetSplitter() ISplitter {
return c.splitter
}
func (c *Connector) OnMessage(msg IMessage) {
logger.Debug("recv msg errorCode: %d cmd: %d, conn: %d data: %s", msg.GetHeader().GetErrCode(), 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())
}