conn.SetDeadline()在超时时会关闭连接吗?

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

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 &lt;- err
}()
select {
case time.After(time.Now() + 1000 * 1000 * 1000 * 5): // Wait for 5 seconds
    // Timed out reading
    go func() {
        &lt;-timeout // We have to read from the sem to prevent mem leaks
    }()
case err := &lt;-timeout:
    // Successfully read
}

huangapple
  • 本文由 发表于 2014年8月1日 09:55:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/25071712.html
匿名

发表评论

匿名网友

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

确定