hhqnotud
hhqnotud

Reputation: 11

how to SetDeadline on DialTCP function and handle timeout error

I am creating a TCP connection to a server but I need to specify a timeout.

How can I achieve such a thing?

This is the simplified code:

tcpserveraddr, err := net.ResolveTCPAddr("tcp", Serveraddr+":"+Serverport)
if err != nil {
    log.Printf("error during address relolution: %v\n", err)
}
serversocket, err := net.DialTCP("tcp", nil, tcpserveraddr)
if err != nil {
    log.Printf("error during serversocket.DialTCP(): %v\n", err)
}

Upvotes: 1

Views: 537

Answers (1)

Emile P.
Emile P.

Reputation: 3962

The most straight forward option is to use net.DialTimeout():

net.DialTimeout(tcpserveraddr.Network(), tcpserveraddr.String(), 5*time.Second)

What you can also do is create a net.Dialer, which gives you more control over the dialing options, and then use DialContext() with your own context (with timeout):

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var d net.Dialer
d.DialContext(ctx, tcpserveraddr.Network(), tcpserveraddr.String())

Upvotes: 1

Related Questions