2017-11-05 03:22
采纳率: 100%
浏览 2.0k


net.DialTCP 似乎是获取net.TCPConn的唯一办法,我不确定在执行 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)
    return nil

图片转代码服务由CSDN问答提供 功能建议

作为 net.DialTCP 似乎是获取 net.TCPConn的唯一方法 ,我不确定在执行 DialTCP 时如何设置超时。 https://golang.org/pkg/net/#DialTCP \ n

  func connectAddress(addr * net.TCPAddr,wg * sync.WaitGroup)错误{
 start:= time.Now()
 conn,err:= net.DialTCP(“ tcp”  ,nil,addr)
如果错误!= nil {
省略:= time.Since(start)
 log.Printf(“ to address to%s in%dms”,addr.String(),elasped.Nanoseconds()/ 1000000)
 conn。  Close()
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drmgg4411 2017-11-05 03:31

    Use net.Dialer with either the Timeout or Deadline fields set.

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

    A variation is to call Dialer.DialContext with a deadline or timeout applied to the context.

    Type assert to *net.TCPConn if you specifically need that type instead of a net.Conn:

    tcpConn, ok := conn.(*net.TCPConn)
    打赏 评论
  • dongzhanbi0027 2018-03-31 23:17

    One can use 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.
    打赏 评论

相关推荐 更多相似问题