在golang中从TCP连接中读取数据

huangapple go评论84阅读模式
英文:

Reading from a tcp connection in golang

问题

在像bytes_read, err := conn.Read(tmp)这样的语句中,我希望读取操作在x秒内尝试进行,如果没有读取开始,我希望代码继续执行检查一些连接,然后再循环回来尝试读取。我可以使用select-case并创建两个goroutine,一个用于尝试读取,另一个用于超时。但是,在超时发生时,代码将继续执行,检查条件,并再次创建一个用于尝试从连接读取的例程,而之前的读取例程仍然存在。我希望在超时发生时,之前的例程能够终止。

对于如何继续进行,你有什么建议吗?

英文:

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

得分: 22

希望这可以帮到你。^_^

for {
    // 设置读取截止时间
    err := conn.SetReadDeadline(time.Now().Add(5 * time.Second))
    if err != nil {
        log.Println("SetReadDeadline 失败:", err)
        // 做其他操作,例如创建新的连接
        return
    }

    recvBuf := make([]byte, 1024)

    n, err = conn.Read(recvBuf[:]) // 接收数据
    if err != nil {
        if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
            log.Println("读取超时:", err)
            // 超时
        } else {
            log.Println("读取错误:", err)
            // 其他错误,做其他操作,例如创建新的连接
        }
    }
}
英文:

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

huangapple
  • 本文由 发表于 2016年1月20日 13:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/34892507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定