2016-01-20 05:54 阅读 318


In a statement like bytes_read, err := conn.Read(tmp), I wish the read be attempted for x seconds and if no read begins I want the code to proceed ahead check some connections and again loop back and try to read. I could use select-case and spawn two goroutines, one attempting the read and the other for timeout. But here, in case of timeout happening first the code will go ahead, check the conditions and again spawn a routine to try to read from the connection while the previous read routines is still alive. I wish that the previous routine dies when timeout takes place.

Any suggestion on how I can proceed?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douguan3470 douguan3470 2016-01-20 08:53

    Hope this can help u. ^_^

    for {
        // set SetReadDeadline
        err := conn.SetReadDeadline(time.Now().Add(5 * time.Second))
        if err != nil {
            log.Println("SetReadDeadline failed:", err)
            // do something else, for example create new conn
        recvBuf := make([]byte, 1024)
        n, err = conn.Read(recvBuf[:]) // recv data
        if err != nil {
            if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
                log.Println("read timeout:", err)
                // time out
            } else {
                log.Println("read error:", err)
                // some error else, do something else, for example create new conn
    点赞 评论 复制链接分享