Search code examples
goconnectiontimeout

Does setting the timeout on the net.Dialer and deadline on the Connection result to the same behaviour?


In Go I create the Connection (with a timeout) from the Dialer:

d := net.Dialer{Timeout: timeout, LocalAddr: *localAddr}
c.conn, err = d.Dial("tcp", address)

However, then I can also set the deadline for the Connection:

 c.conn.SetDeadline(time.Now().Add(timeout));

Is this redundant, or setting the timeout and the deadline here have functional differences?


Solution

  • These are completely different.

    The net.Dialer is used to establish connections. The deadline (or timeout) applies to connection establishment. Quoting the docs for the Timeout and Deadline fields respectively:

    Timeout is the maximum amount of time a dial will wait for a connect to complete.

    Deadline is the absolute point in time after which dials will fail.

    On the other hand, a net.Conn holds an established connection. The timeout applies to read/write operations on the connection. This is also clearly stated in the docs for net.Conn:

    SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

    Note that this is a common set of timeouts (among others): one for connection establishment, another for operations on an established connection.