如何在Go中中止net.Dial调用?

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

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.DialerTimeoutDeadline字段,并且可以使用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)

huangapple
  • 本文由 发表于 2017年9月18日 20:23:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/46279205.html
匿名

发表评论

匿名网友

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

确定