英文:
Does conn.SetDeadline() close the connection if it times out
问题
我有一个使用conn.SetDeadline()的Golang项目。如果由于读取超时而引发EOF错误,Go会自动关闭连接吗?
我有一个设置,在网络连接上需要等待一定的时间才能接收输出,如果输出没有到达,那么它必须发送一个QUIT命令。我没有设计网络应用程序,所以重新设计协议不是一个选项。
理想情况下,当由于SetDeadline超时而引发EOF时,我希望goroutine被唤醒,但连接不关闭。
提前感谢你的帮助!
英文:
I have a Golang project that utilizes conn.SetDeadline(). If a an EOF error is thrown because a read timed out, does Go automatically close the connection?
I have a setup where I need to wait a certain amount of time on a network connection for output to arrive, and if the output doesn't arrive, then it has to send a QUIT command. I haven't designed the network application, so redesigning the protocol isn't an option
Ideally, when an EOF is thrown because of SetDeadline timing out, then I would want the goroutine to awaken, but not for the connection to close
Thank you for your help in advance!
答案1
得分: 1
显然不是这样的。我的解决方法(嗯,并不是解决方法,而是正确的做法)如下:
timeout := make(chan error)
buf := make([]byte, 32)
go func() {
_, err := conn.Read(buf)
timeout <- err
}()
select {
case time.After(time.Now() + 1000 * 1000 * 1000 * 5): // 等待5秒钟
// 读取超时
go func() {
<-timeout // 我们必须从信道中读取以防止内存泄漏
}()
case err := <-timeout:
// 成功读取
}
英文:
Apparently it doesn't. My workaround (well, not workaround, but the correct way to do this) was like so
timeout := make(chan error)
buf := make([]byte, 32)
go func() {
_, err := conn.Read(buf)
timeout <- err
}()
select {
case time.After(time.Now() + 1000 * 1000 * 1000 * 5): // Wait for 5 seconds
// Timed out reading
go func() {
<-timeout // We have to read from the sem to prevent mem leaks
}()
case err := <-timeout:
// Successfully read
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论