6

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?

3
  • 2
    Maybe what u need is only the SetReadDeadline for conn. if netErr, ok := err.(net.Error); ok && netErr.Timeout() doSomething Commented Jan 20, 2016 at 6:50
  • @Justlike Thanks! Thats what I need. But can you help me with the syntax. I am using err2 := conn.SetReadDeadline(time.Now().Add(5 * time.Second)) | bytes_read, err := conn.Read(tmp) | err.Timeout() which results in the error that err.Timeout undefined (type error has no field or method Timeout). I want to check whether Timeout() is true or false Commented Jan 20, 2016 at 8:20
  • ^_^ Check the post below. Commented Jan 20, 2016 at 8:54

1 Answer 1

23

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
        return
    }

    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
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.