Is golang conn.setdeadline for the next operation only or forever?

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

Is golang conn.setdeadline for the next operation only or forever?

问题

在下面的代码中:

conn.SetDeadline(time.Now().Add(time.Minute)) 
// 读/写操作,仅一次             
conn.SetDeadline(time.Time{})    // 取消截止时间          

“取消”操作是必要的吗?也就是说,如果我不取消它,连接将在一分钟后超时,无论后续操作成功与否?

或者,SetDeadline命令仅适用于紧随其后的操作,而在该操作成功后,截止时间会自动消失?

英文:

In the code below:

conn.SetDeadline(time.Now().Add(time.Minute)) 
//read/write operation, only once             
conn.SetDeadline(time.Time{})    //cancel deadline          

Is the "cancel" operation necessary? i.e. If I do not cancel it, the connection will timeout in one minute, no matter if following operation succeeds/fails?

Or, the SetDeadline command only applys to the immediate following operation, and after that operation succeeds, the deadline automatically vanishes?

答案1

得分: 1

请参考Conn interface中的注释。

// 截止时间是一个绝对时间,在此之后,I/O操作将失败而不是阻塞。截止时间适用于所有未来和待处理的I/O操作,而不仅仅是紧接着的Read或Write调用。超过截止时间后,可以通过设置未来的截止时间来刷新连接。

如上所述,截止时间适用于“所有未来”的I/O操作。如果在截止时间过去后继续使用连接,将会收到“包装了os.ErrDeadlineExceeded的错误”。如果您希望再次使用连接,您需要将截止时间设置为未来的时间或零值(例如conn.SetDeadline(time.Time{}))。

需要注意的是,超过截止时间并不会关闭连接。在收到os.ErrDeadlineExceeded后,您仍然可以设置新的截止时间(或清除截止时间)并继续发送/接收数据。不应该假设收到错误意味着连接已关闭(如果您希望关闭连接,请确保调用close())。

英文:

See the comments for the Conn interface

>// A deadline is an absolute time after which I/O operations
// fail instead of blocking. The deadline applies to all future
// and pending I/O, not just the immediately following call to
// Read or Write. After a deadline has been exceeded, the
// connection can be refreshed by setting a deadline in the future.

As stated the deadline applies to "all future" I/O. If you use the connection after the deadline has passed you will get "an error that wraps os.ErrDeadlineExceeded". If you wish to use the connection again you will need to set the deadline to a future or zero value (i.e. conn.SetDeadline(time.Time{})).

It is important to note that exceeding the deadline does not close the connection. After receiving an os.ErrDeadlineExceeded you can still set a new deadline (or clear the deadline) and continue to send/receive. You should not assume that receiving an error means the connection is closed (if that is what you want ensure you call close()).

huangapple
  • 本文由 发表于 2022年7月4日 09:15:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/72850929.html
匿名

发表评论

匿名网友

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

确定