/
agent_link_client.go
86 lines (75 loc) · 1.64 KB
/
agent_link_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
package agentlink
import (
"errors"
"io"
"net"
"strconv"
"github.com/bitwormhole/starter/vlog"
)
func NewClient(config *Config) (*Client, error) {
if config == nil {
return nil, errors.New("config==nil")
}
client := &Client{}
err := client.Init(config)
if err != nil {
return nil, err
}
return client, nil
}
////////////////////////////////////////////////////////////////////////////////
type Client struct {
config Config
conn2close io.Closer
}
func (inst *Client) Init(config *Config) error {
inst.config = *config
return nil
}
func (inst *Client) log(p ...interface{}) {
p2 := make([]interface{}, 0)
p2 = append(p2, "agentlink.client: ")
p2 = append(p2, p...)
vlog.Info(p2...)
}
func (inst *Client) Connect() error {
cfg := inst.config
addr := cfg.Host + ":" + strconv.Itoa(cfg.Port)
inst.log("connect to " + addr)
conn, err := net.Dial("tcp", addr)
if err != nil {
return err
}
inst.log("connected")
go inst.handleConnection(conn)
return nil
}
func (inst *Client) Disconnect() error {
cc := inst.conn2close
inst.conn2close = nil
if cc == nil {
return nil
}
return cc.Close()
}
func (inst *Client) handleConnection(conn net.Conn) {
defer conn.Close()
defer func() {
inst.log("connection closed")
recover()
}()
inst.conn2close = conn
err := inst.handleConnection2(conn)
if err != nil {
vlog.Error(err)
}
}
func (inst *Client) handleConnection2(conn net.Conn) error {
h := inst.config.HandlerFactory.NewHandler()
con2 := AgentLinkConn{}
err := con2.Init(conn, h)
if err != nil {
return err
}
return con2.RunLoop()
}