user3740387
user3740387

Reputation: 367

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?

Upvotes: 6

Views: 21232

Answers (1)

Justlike
Justlike

Reputation: 1504

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

Upvotes: 22

Related Questions