1024programmer Java How to set timeout when executing net.DialTCP in golang?

How to set timeout when executing net.DialTCP in golang?

1> Cerise Limón..:


Use net.Dialer with either timeout or deadline field set.

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

A variation is to call Dialer.DialContext and apply a deadline or timeout to the context.

*net.TCPConnIf you specifically need this type instead of the following, type assert net.Conn:

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

2> jeanluc..:


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.
 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/771096

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索