至于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
}
Run Code Online (Sandbox Code Playgroud)
Cer*_*món 11
使用net.Dialer与任一超时或截止日期字段集.
d := net.Dialer{Timeout: timeout}
conn, err := d.Dial("tcp", addr)
if err != nil {
// handle error
}
Run Code Online (Sandbox Code Playgroud)
一种变体是调用Dialer.DialContext,并将截止时间或超时应用于上下文.
*net.TCPConn如果您特别需要该类型而不是以下类型,请键入assert net.Conn:
tcpConn, ok := conn.(*net.TCPConn)
Run Code Online (Sandbox Code Playgroud)
一个可以使用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.
Run Code Online (Sandbox Code Playgroud)