-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
273 lines (230 loc) · 6.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
ssh-keep
keep your ssh connection survive from network fluctuation or wifi switching
Author: [email protected]
License: GPLv2
Site: https://github.com/yurenchen000/ssh-keep
*/
package main
import (
"bufio"
"flag"
"io"
"math/rand"
"net"
"os"
"time"
. "pkt"
)
var build_version string
var ServerAddr = "127.0.0.1:1234"
var flgServerAddr = flag.String("server", ServerAddr, "connect to server")
var flgVersion = flag.Bool("version", false, "current version: "+build_version)
var conn_gone = false
var last_read time.Time = time.Now() //last read from server
var last_unack time.Time
const AckTimeOut = 3
type Session struct {
Sess
connB net.Conn
readI chan []byte
ctxI chan int
}
func main() {
flag.Parse()
if *flgVersion {
Println("version:", build_version)
return
}
// pseudo random number
rand.Seed(time.Now().UnixNano())
stdinReader := bufio.NewReader(os.Stdin)
stdoutWriter := bufio.NewWriter(os.Stdout)
sess := Session{
Sess: Sess{
Sess_id: rand.Uint32(),
Pend_map: make(map[uint16][]byte),
},
ctxI: make(chan int, 10), // chan to broadcast conn lost,
readI: make(chan []byte, 10), // chan to send msg,
}
// Connect to the server
conn, err := connect(*flgServerAddr, stdoutWriter, &sess)
if err != nil {
Println("Error connecting to server:", err)
return
}
defer conn.Close()
//send sess ctx
Println("send-sess:", "#", sess.Recv_mid, sess.Sess_id)
sess.SendSession(conn)
//wait sess
_, _, rid := sess.ReadMsg(conn) // not up recv_mid
if rid == -1 {
Println("-- reading from Server: Error")
return
}
Println("recv-sess:", "#", rid, sess.Self_mid)
go readFromServer(conn, stdoutWriter, &sess)
go readFromStdin(sess.readI, conn, sess.ctxI, &sess)
suckStdin(stdinReader, &sess)
// select {}
}
// Try to connect to the server
func connect(host string, stdoutWriter *bufio.Writer, sess *Session) (net.Conn, error) {
conn, err := net.Dial("tcp", host)
if err != nil {
return nil, err
}
// Start a goroutine to monitor the connection
go func() {
for {
// Check if the connection is still alive
now := time.Now()
wait_time := now.Sub(last_unack)
if conn_gone ||
last_unack.After(last_read) &&
wait_time > time.Second*AckTimeOut {
// The connection is lost, try to reconnect
Println("\n-- conn lost, trying re-conn...", conn, wait_time.Round(time.Millisecond), conn_gone)
close(sess.ctxI) //notify readFromStdin stop
sess.ctxI = make(chan int, 10)
for {
newConn, err := net.Dial("tcp", host)
if err == nil {
conn_gone = false
Println("++ conn re-established", conn)
// Replace the old connection with the new one
conn.Close()
conn = newConn
// send-sess ctx
Println("send-sess:", "#", sess.Recv_mid, sess.Sess_id)
sess.SendSession(conn)
// wait-sess
_, _, rid := sess.ReadMsg(conn) // not up recv_mid
if rid == -1 {
Println("-- reading from Server: Error")
conn_gone = true
time.Sleep(time.Second * 3)
// continue //re-conn
break
}
last_read = time.Now()
Println("recv-sess:", "#", rid, sess.Self_mid)
Println("re-send: ", &sess, rid, sess.Self_mid)
ret := sess.Pend_map.ReSend(uint16(rid), sess.Self_mid, conn)
if ret == -1 { //lost mid
Println("#### exit, lost mid:")
os.Exit(1)
} else if ret == -2 {
Println("#### lost conn? break")
break
}
// Restart the goroutine with the new connection
go readFromServer(conn, stdoutWriter, sess)
go readFromStdin(sess.readI, conn, sess.ctxI, sess)
Println("reconn wait:", 20)
time.Sleep(time.Second * 20)
break
}
// Wait a moment before trying to reconnect again
time.Sleep(time.Second)
}
}
time.Sleep(time.Second)
}
}()
Println("++ Connection to server established", conn)
return conn, nil
}
func readMsg(reader net.Conn) (out []byte, mid int) {
buf := make([]byte, 4)
n, err := io.ReadFull(reader, buf)
Println("readMsgH:", err, buf)
if err != nil || n != 4 {
return nil, -1
}
pkt := DecHead(buf)
mid = int(pkt.Mid)
out = make([]byte, pkt.Len)
n, err = io.ReadFull(reader, out)
Println("readMsgB:", err, out)
if err != nil {
return nil, -1
}
return out, mid
}
func readFromServer(reader net.Conn, writer *bufio.Writer, sess *Session) {
Println("++ reading from Server..")
for {
// Read the response from the server
buf, mid, rid := sess.ReadMsg(reader)
if mid == -1 {
Println("-- reading from Server: Error")
return
}
if mid <= int(sess.Recv_mid) && int(sess.Recv_mid)-mid < 3000 { //not loopback
continue //drop dup pkt
}
sess.Recv_mid = uint16(mid)
// Println("= recv_msg:", recv_mid, "len", len(buf))
last_read = time.Now()
LogPkgInfo("- client recv:", " \033[32m", MsgInfo(uint16(mid), uint16(rid), len(buf)), "\033[0m")
LogPkgBody("\n\033[32m", (BufMax(buf, 50)), "\033[0m")
err := writeToStdout(buf, writer)
if err != nil {
Println("-- writing to stdout: Error", err)
return
}
}
}
func suckStdin(reader *bufio.Reader, sess *Session) {
buf := make([]byte, 1024)
for {
// Read from os.Stdin
n, err := reader.Read(buf)
if err != nil || n == 0 {
Println("Error reading stdin:", err, n)
return
}
tmp := make([]byte, n)
// Println("arr len:", len(tmp), cap(tmp))
copy(tmp, buf)
sess.readI <- tmp
}
}
func readFromStdin(read <-chan []byte, writer net.Conn, ctx <-chan int, sess *Session) {
Println("++ reading from Stdin chan..")
for {
select {
case val, ok := <-ctx: //read OR closed
Println("-- reading from Stdin chan: close:", val, ok)
return
case input, ok := <-read:
sess.Self_mid++
if !ok {
Println("readA chan fail:", ok)
}
now := time.Now()
if last_unack.Before(last_read) { //had ack
last_unack = now //not ack
}
LogPkgInfo("- client send:", "\033[33m", MsgInfo(sess.Self_mid, sess.Recv_mid, len(input)), "\033[0m", now.Sub(last_unack).Round(time.Millisecond)) // > 10s maybe lost // should < 0
LogPkgBody("\n\033[33m", BufMax(input, 50), "\033[0m")
// Send the input to the server
err := sess.SendMsg(input, writer)
if err != nil {
conn_gone = true
Println("-- Error writing to server:", err)
return
}
}
}
}
func writeToStdout(output []byte, writer *bufio.Writer) error {
_, err := writer.Write(output)
if err != nil {
return err
}
return writer.Flush()
}