gpt4 book ai didi

go - conn.SetDeadline() 是否在超时时关闭连接

转载 作者:IT王子 更新时间:2023-10-29 02:17:05 27 4
gpt4 key购买 nike

我有一个使用 conn.SetDeadline() 的 Golang 项目。如果因为读取超时而抛出 EOF 错误,Go 会自动关闭连接吗?

我有一个设置,我需要在网络连接上等待一定时间才能让输出到达,如果输出没有到达,那么它必须发送一个 QUIT 命令。我没有设计网络应用程序,因此无法重新设计协议(protocol)

理想情况下,当由于 SetDeadline 超时而抛出 EOF 时,我希望 goroutine 被唤醒,而不是连接关闭

提前感谢您的帮助!

最佳答案

显然不是。我的解决方法(好吧,不是解决方法,而是正确的方法)是这样的

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
}

关于go - conn.SetDeadline() 是否在超时时关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com