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?
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With