dongmi9494 2017-09-18 12:23
浏览 17
已采纳

如何在Go中终止网络拨号?

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条回答 默认 最新

  • dongmei8511 2017-09-18 12:45
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?