【发布时间】:2014-11-22 17:38:00
【问题描述】:
我需要读取 UDP 流量,直到达到超时。我可以通过在 UDPConn 上调用 SetDeadline 并循环直到我收到 I/O 超时错误来做到这一点,但这似乎是 hack-ish(基于错误条件的流控制)。以下代码 sn -p 似乎更正确,但不会终止。在生产中,这显然会在 goroutine 中执行;为简单起见,它被写为 main 函数。
package main
import (
"fmt"
"time"
)
func main() {
for {
select {
case <-time.After(time.Second * 1):
fmt.Printf("Finished listening.\n")
return
default:
fmt.Printf("Listening...\n")
//read from UDPConn here
}
}
}
为什么给定的程序没有终止?基于https://gobyexample.com/select、https://gobyexample.com/timeouts 和https://gobyexample.com/non-blocking-channel-operations,我希望上面的代码选择默认情况一秒钟,然后采用第一种情况并跳出循环。我该如何修改上面的sn-p,以达到预期的循环读取效果,直到发生超时?
【问题讨论】:
-
如果您将
break更改为return,该功能将在持续时间完成时完成。您目前正在永远循环并每秒打印Finished。 -
@chendesheng 我相信 time.After 的使用是惯用的(见golang.org/pkg/time/#example_After)感谢你们两位对break语句的catch;我已经更新了sn-p。不过,程序仍然没有终止
-
@chendesheng 我忘了说:我确实尝试使用 time.Tick 代替,但仍然出现无限循环行为
-
使用时间我错了。打勾,也无济于事。而 OneOfOne 的答案是正确的。
标签: concurrency go network-programming udp