英文:
Idiomatic way to timeout TCP handshake in Go
问题
在Go语言中,对于超时TCP会话(例如初始协议握手),惯用的方式是什么?假设有一个处理TCP会话的goroutine。我可以启动它,然后启动一个time.After()
定时器,然后使用select
同时监听它们,如果超时触发,就可以继续执行其他操作。
然而,这意味着即使没有人再需要它,TCP goroutine仍会在超时后保持TCP连接的活动状态。
英文:
What is the idiomatic way in Go to timeout a TCP conversation, such as initial protocol handshake? Let's say there is a goroutine that handles the TCP conversation. I can launch it, then launch a time.After()
, then select
for both of them and if timeout was hit, proceed on doing other stuff.
However, that means that the TCP goroutine will linger on after the timeout keeping the TCP connection alive even though nobody will ever need it.
答案1
得分: 4
超时初始连接,您可以使用net.DialTimeout
,或者更具体地,在net.Dialer
上设置Timeout
参数。
在使用TCP连接时,如果需要超时单个操作,可以在连接上使用SetDeadline
,SetReadDeadline
,或者SetWriteDeadline
。
如果需要立即取消连接上的操作,在Go中的做法是通过Close()
关闭连接。连接对于并发操作是安全的,您可以从除了在网络操作上阻塞的goroutine之外的goroutine中调用Close()
。
英文:
To timeout the initial connection, you use net.DialTimeout
, or more specifically, set the Timeout
parameter on a net.Dialer
.
To timeout individual operations on a TCP connection while it's in use, you use SetDeadline
, SetReadDeadline
, or SetWriteDeadline
on the connection.
If you need to cancel operations on a connection immediately, the way to do that in Go is to Close()
the connection. Connections are safe for concurrent operations, and you can call Close()
from a goroutine other than the one blocking on the network operation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论