-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpclient.go
66 lines (57 loc) · 1.38 KB
/
tcpclient.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
package roshan
import (
"fmt"
"net"
"strconv"
"github.com/fengdingfeilong/roshan/handler"
)
//Client tcpserver client
type Client struct {
tcpSCBase
//SocketConnected socket connected
SocketConnected func(conn net.Conn)
//BeforeClose before close the socket
BeforeClose func(conn net.Conn)
workConn net.Conn
}
//NewClient create client
func NewClient() *Client {
var c Client
c.handlerManager = &handler.Manager{}
c.HBSendInterval = 5
c.HBTimeout = 10
return &c
}
//Connect connect to server
func (client *Client) Connect(ip string, port int) bool {
conn, err := net.Dial("tcp", ip+":"+strconv.Itoa(port))
if err != nil {
loginfo(err.Error(), err)
return false
}
cc := newConnContext(conn)
cc.socketErrOccured = client.handleSocErr
client.workConn = cc
cc.SetSK(client.key)
if client.SocketConnected != nil {
client.SocketConnected(cc)
}
go client.handleConn(cc)
return true
}
func (client *Client) handleSocErr(cc *connContext, err error) {
loginfo(fmt.Sprintf("socket error: %s", err.Error()), err)
client.closeSocket(cc)
}
// func (client *Client) closeSocket(cc *connContext) {
// cc.Close()
// }
//Close close the connection
func (client *Client) Close() {
if client.BeforeClose != nil {
temp := client.workConn
client.BeforeClose(temp)
}
client.workConn.Close()
client.workConn = nil
}