Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a tcp connection in golang

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?

like image 996
user3740387 Avatar asked Dec 05 '22 01:12

user3740387


1 Answers

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
        }
    }
}
like image 52
Justlike Avatar answered Dec 12 '22 20:12

Justlike