I have this code:
for { // infinite loop
// connect
conn, err := net.Dial("tcp", forward_ip_port)
if L.IsError(err, `Failed to connect to `+forward_ip_port) {
time.Sleep(time.Second)
continue
}
// TODO: query 100 data from last one, translate to string
arr := PG.QStrArr(`
SELECT x1.id || '#' || x1.data -- *snip, some other column*
FROM station_logs x1
WHERE x1.id > ` + I.ToS(last_id) + `
ORDER BY x1.id
LIMIT ` + I.ToS(limit))
if len(arr) == 0 {
time.Sleep(time.Second)
continue
}
// write to server
fmt.Println(`Start sending ` + I.ToStr(len(arr)) + ` records`)
for _, txt := range arr {
n, err := fmt.Fprintf(conn, txt+"
")
L.IsError(err, `Failed to deliver `+txt)
fmt.Print(txt)
fmt.Println(` ` + I.ToStr(n) + ` bytes written`)
}
//L.IsError(conn.SetReadDeadline(time.Now().Add(time.Second*3)), `Failed to set deadline`)
io.Copy(os.Stdout, conn)
// close connection
conn.Close()
// write last id to file
last := arr[len(arr)-1]
last = S.LeftOf(last, `#`)
last_id := S.ToI(last)
last_id_str := I.ToS(last_id)
err = ioutil.WriteFile(last_id_file, []byte(last_id_str), 0644)
L.IsError(err, `Failed to write `+last_id_str+` to `+last_id_file)
// sleep for 1 seconds
time.Sleep(time.Second)
}
The purpose of this code is to deliver data to server, with interval of 1 second. The server will reply line-by-line (similar to echo server) and wait for next line of items, and will never close the connection.
The problem with code above is, I could not interrupt the io.Copy
to disconnect or resume sending next batch.
What's better way to do this?