/
singleConnection.go
executable file
·112 lines (86 loc) · 2.2 KB
/
singleConnection.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
package main
/*
sender通过sendData调用SingleConnection:
s.connnection = SingleConnectionInit(address,bakAddress)
result := s.sendData(data.Bytes(),s.connnection.getConn())
*/
import (
"net"
"logd/lib"
"logd/loglib"
)
type SingleConnection struct {
addr string
bakAddr string
currentAddr string
conn *net.TCPConn
failedTimes int
max_try_times int
}
func SingleConnectionInit(address string,bakAddress string) (sc *SingleConnection){
sc = new(SingleConnection)
sc.addr = address
sc.currentAddr = sc.addr
sc.bakAddr = bakAddress
sc.failedTimes = 0
sc.max_try_times = 30
sc.initConnection()
return sc
}
//init conn list from addrMap
func (sc *SingleConnection) initConnection() {
newConn,err := createSingleConnection(sc.currentAddr)
if err != nil {
loglib.Error("init err:" + err.Error())
}else {
sc.conn = newConn
}
lib.CheckError(err)
}
func createSingleConnection(address string) (conn *net.TCPConn,err error) {
tcpAddr, err := net.ResolveTCPAddr("tcp4", address)
lib.CheckError(err)
if err != nil {
return nil,err
}
conn, err = net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
loglib.Error("get connection from " + address + " failed! Error:" + err.Error())
return nil,err
}else {
loglib.Info("get connection from " + address + " success! remote addr " + conn.RemoteAddr().String() )
}
lib.CheckError(err)
return conn,nil
}
func (sc *SingleConnection) reconnect(conn *net.TCPConn) {
if (sc.failedTimes < sc.max_try_times) {
newConn,err := createSingleConnection(sc.currentAddr)
if err != nil {
sc.failedTimes++
}else {
sc.conn = newConn
sc.failedTimes = 0
}
}else {
tmpAddr := sc.currentAddr
sc.currentAddr = sc.bakAddr
sc.bakAddr = tmpAddr
sc.failedTimes = 0
loglib.Warning("try bakup address:" + sc.currentAddr)
newConn,err := createSingleConnection(sc.currentAddr)
if err == nil {
loglib.Warning("use bakup address:" + sc.currentAddr)
sc.conn = newConn
}
}
}
func (sc *SingleConnection) getConn() *net.TCPConn {
//log.Println("get connection's remote addr ",sc.conn)
return sc.conn
}
func (sc *SingleConnection) close() {
if sc.conn != nil {
sc.conn.Close()
}
}