/
client.go
127 lines (113 loc) · 2.34 KB
/
client.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package Znet
import (
"github.com/DoChEnGzZ/Czinx/Zinterface"
"go.uber.org/zap"
"net"
"sync"
)
const(
DefaultIp="127.0.0.1"
DefaultPort=8080
)
type Client struct {
ip string
port int
msgHandler *MsgHandler
conn Zinterface.ConnectionI
exitChan chan struct{}
mutex sync.Mutex
beforeStart Zinterface.ConnectionFunc
afterStart Zinterface.ConnectionFunc
beforeStop Zinterface.ConnectionFunc
isOkChan chan bool
}
func NewClient(ip string,port int)*Client {
//log.SetFlags(log.Ltime|log.Llongfile)
return &Client{
ip: ip,
port: port,
msgHandler: NewMsgHandler(1, 1),
exitChan: make(chan struct{}),
mutex: sync.Mutex{},
isOkChan: make(chan bool),
}
}
func (c *Client)Start(){
//启动客户端
go func() {
addr:=&net.TCPAddr{
IP: net.ParseIP(c.ip),
Port: c.port,
Zone: "",
}
conn, err := net.DialTCP("tcp",nil,addr)
if err != nil {
zap.L().Error("[Client]start error"+err.Error())
}
c.conn=NewConnection(c,conn,0,c.msgHandler)
c.isOkChan<-true
go c.conn.Start()
select {
case <-c.exitChan:
c.conn.Stop()
}
}()
}
func (c *Client) Stop(){
//log.Println("[Client]Stop")
c.exitChan<- struct{}{}
}
func (c *Client) Serve() {
//
}
func (c *Client) Conn()Zinterface.ConnectionI{
return c.conn
}
func (c *Client)GetMsgHandle()Zinterface.MsgHandleI{
return c.msgHandler
}
func (c *Client) AddRouter(msgId uint32,r Zinterface.RouterI){
err := c.msgHandler.AddRouter(msgId, r)
if err != nil {
zap.L().Error("[Client]add router error")
}
}
func (c *Client) SendMessage(id uint32, s string) {
//fmt.Printf("id:%d,s:%s\n",id,s)
//等待连接建立完成
select {
case <-c.isOkChan:
break
}
err := c.Conn().Send(id, []byte(s))
if err != nil {
zap.L().Error(err.Error())
}
}
func (c *Client) GetManager()Zinterface.ManagerI{
return nil
}
func (c *Client) CallAfterConnect(i Zinterface.ConnectionI){
if c.afterStart!=nil{
c.afterStart(i)
}
}
func (c *Client)CallBeforeConnect(i Zinterface.ConnectionI){
if c.beforeStart!=nil{
c.beforeStart(i)
}
}
func (c *Client)CallBeforeStop(i Zinterface.ConnectionI){
if c.beforeStop!=nil{
c.beforeStop(i)
}
}
func (c *Client)SetAfterConnect(f Zinterface.ConnectionFunc){
c.afterStart=f
}
func (c *Client)SetBeforeConnect(f Zinterface.ConnectionFunc){
c.beforeStart=f
}
func (c *Client)SetBeforeStop(f Zinterface.ConnectionFunc){
c.beforeStop=f
}