forked from ejoy/goscon
-
Notifications
You must be signed in to change notification settings - Fork 3
/
localconn.go
64 lines (54 loc) · 1.32 KB
/
localconn.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
package main
import (
"net"
"github.com/ejoy/goscon/scp"
"github.com/xjdrew/glog"
)
// LocalSCPConn .
type LocalSCPConn struct {
*SCPConn
}
// ReuseConn reused conn
func reuseConn(connForReused *scp.Conn) (scon *scp.Conn, err error) {
remoteAddr := connForReused.RemoteAddr()
tcpConn, err := net.Dial(remoteAddr.Network(), remoteAddr.String())
if err != nil {
glog.Errorf("connect to <%s> failed: %s when reuse conn", remoteAddr.String(), err.Error())
return
}
scon, err = scp.Client(tcpConn, &scp.Config{
ConnForReused: connForReused,
TargetServer: connForReused.TargetServer(),
})
if err != nil {
glog.Errorf("scp reuse conn failed: %s", err.Error())
return
}
err = scon.Handshake()
if err != nil {
glog.Errorf("scp reuse handshake failed: client=%s, err=%s", scon.RemoteAddr().String(), err.Error())
scon.Close()
return
}
return
}
func (c *LocalSCPConn) reuseConn() {
scon, err := reuseConn(c.Conn)
if err != nil {
return
}
if !c.ReplaceConn(scon) {
scon.Close()
}
}
// startWait start reuse timer and reuse conn
func (c *LocalSCPConn) startWait() {
c.SCPConn.startWait()
go c.reuseConn() // reuse the upstream scp.conn
}
// NewLocalSCPConn .
func NewLocalSCPConn(scon *scp.Conn) *LocalSCPConn {
scpConn := NewSCPConn(scon)
localSCPConn := &LocalSCPConn{SCPConn: scpConn}
return localSCPConn
}