如何在golang中执行net.DialTCP时设置超时?

时间:2017-11-05 03:22:07

标签: go

由于net.DialTCP似乎是获取net.TCPConn的唯一方式,因此我不确定如何在执行DialTCP时设置超时。 https://golang.org/pkg/net/#DialTCP

func connectAddress(addr *net.TCPAddr, wg *sync.WaitGroup) error {
    start := time.Now()
    conn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        log.Printf("Dial failed for address: %s, err: %s", addr.String(), err.Error())
        return err
    }
    elasped := time.Since(start)
    log.Printf("Connected to address: %s in %dms", addr.String(), elasped.Nanoseconds()/1000000)
    conn.Close()
    wg.Done()
    return nil
}

2 个答案:

答案 0 :(得分:10)

在设置net.DialerTimeout字段时使用Deadline

d := net.Dialer{Timeout: timeout}
conn, err := d.Dial("tcp", addr)
if err != nil {
   // handle error
}

变体是通过将Dialer.DialContextdeadline应用于上下文来调用timeout

如果您特别需要该类型而不是*net.TCPConn,则键入断言为net.Conn

tcpConn, ok := conn.(*net.TCPConn)

答案 1 :(得分:3)

可以使用net.DialTimeout

func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
    DialTimeout acts like Dial but takes a timeout.

    The timeout includes name resolution, if required. When using TCP, and the
    host in the address parameter resolves to multiple IP addresses, the timeout
    is spread over each consecutive dial, such that each is given an appropriate
    fraction of the time to connect.

    See func Dial for a description of the network and address parameters.