douquan3294 2016-01-20 05:54
浏览 919
已采纳

从Golang中的TCP连接读取

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?

  • 写回答

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
            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
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码