dtmm0148603 2017-10-13 11:56
浏览 26

使io.Copy可中断以每n秒发送数据到块中?

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
    • ¥20 关于URL获取的参数,无法执行二选一查询
    • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
    • ¥15 marlin编译错误,如何解决?
    • ¥15 有偿四位数,节约算法和扫描算法
    • ¥15 VUE项目怎么运行,系统打不开
    • ¥50 pointpillars等目标检测算法怎么融合注意力机制
    • ¥20 Vs code Mac系统 PHP Debug调试环境配置
    • ¥60 大一项目课,微信小程序
    • ¥15 求视频摘要youtube和ovp数据集