英文:
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
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论