2016-01-20 05:54
浏览 638


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?

图片转代码服务由CSDN问答提供 功能建议

在类似bytes_read,err:= conn.Read(tmp)的语句中,我希望尝试读取x 秒,如果没有开始读取,我希望代码继续进行,检查一些连接,然后再次循环返回并尝试读取。 我可以使用select-case并生成两个goroutine,一个尝试读取,另一个尝试超时。 但是在这里,如果发生超时,首先将继续执行代码,检查条件,然后在先前的读取例程仍然存在的情况下再次生成例程以尝试从连接读取。 我希望前面的例程在超时时消失。


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 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
    打赏 评论

相关推荐 更多相似问题