英文:
How to abort a net.Dial call in Go?
问题
我有一个客户端试图连接到一个服务器。
我需要能够终止客户端并中止这个拨号尝试。这可能吗?我该如何做到这一点?
超时显然超过了30秒,因为测试会阻塞,直到30秒过去,拨号调用才会失败。
我们可以自己指定超时时间吗?
英文:
I have a client who try to connect to a server.
I need to be able to terminate the client and abort this Dial attempt. Is this possible ? How could I do that ?
The timeout is apparently longer than 30s since the test blocks until the 30s elapse without a failure of the Dial call.
Can we specify a timeout ourself ?
答案1
得分: 9
net.Dialer
有Timeout
和Deadline
字段,并且可以使用DialContext
中的上下文,允许设置超时和取消。
您可以参考DialTimeout
来了解如何设置基本的Dialer:
func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
d := Dialer{Timeout: timeout}
return d.Dial(network, address)
}
以下是使用context.Context
的示例:
var d Dialer
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return d.DialContext(ctx, network, address)
英文:
The net.Dialer
has Timeout
and Deadline
fields, and also can use a context with DialContext
which allows for timeout and cancelation.
You can refer to DialTimeout
to see how to setup the basic Dialer:
func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
d := Dialer{Timeout: timeout}
return d.Dial(network, address)
}
And an example with a context.Context
:
var d Dialer
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return d.DialContext(ctx, network, address)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论