Idiomatic way to timeout TCP handshake in Go

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

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连接时,如果需要超时单个操作,可以在连接上使用SetDeadlineSetReadDeadline,或者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.

huangapple
  • 本文由 发表于 2015年5月26日 00:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/30442624.html
匿名

发表评论

匿名网友

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

确定