Dial with context and control deadlines
Dial with context and control deadlines
Dialer.DialContext uses a context for connection establishment. Cancellation after a successful dial does not automatically close the connection. For subsequent I/O, set read/write deadlines or arrange for the connection owner to close it on cancellation. Deadlines are absolute times, not durations or automatically renewed idle limits.
package main
import ( "context" "fmt" "io" "net" "time")
func check(e error) { if e != nil { panic(e) }}func main() { l, e := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) check(e) defer l.Close() check(l.SetDeadline(time.Now().Add(2 * time.Second))) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() var d net.Dialer c, e := d.DialContext(ctx, "tcp4", l.Addr().String()) check(e) defer c.Close() s, e := l.Accept() check(e) defer s.Close() cancel() check(c.SetWriteDeadline(time.Now().Add(time.Second))) check(s.SetReadDeadline(time.Now().Add(time.Second))) _, e = c.Write([]byte("x")) check(e) p := make([]byte, 1) _, e = io.ReadFull(s, p) check(e) fmt.Println(ctx.Err() != nil, string(p))}Cancel releases context resources, but the established connection remains usable. A dial timeout is not a total request timeout. Recompute the remaining request budget for later operations when needed; close on early returns.
Expected output:
true xDetect a read deadline and reset it
package main
import ( "errors" "fmt" "io" "net" "os" "time")
func check(e error) { if e != nil { panic(e) }}func main() { a, b := net.Pipe() defer a.Close() defer b.Close() check(a.SetReadDeadline(time.Now().Add(-time.Second))) p := make([]byte, 1) _, e := a.Read(p) fmt.Println(errors.Is(e, os.ErrDeadlineExceeded)) check(a.SetReadDeadline(time.Now().Add(time.Second))) check(b.SetWriteDeadline(time.Now().Add(time.Second))) done := make(chan error, 1) go func() { _, e := b.Write([]byte("y")); done <- e }() _, e = io.ReadFull(a, p) check(e) check(<-done) fmt.Println(string(p))}A deadline affects pending and future operations of the selected direction. After expiration, a future deadline permits another attempt; zero time clears the deadline. errors.Is checks the wrapped deadline error. A timeout can accompany partial data; check n before handling err. Not every timeout is caused by a connection deadline.
Expected output:
trueyTry it locally
Set a past write deadline on one end of net.Pipe; attempt a write and print whether it is os.ErrDeadlineExceeded.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Networking 03: Dial with context and control deadlines
Check the lesson objective before moving on.
What happens to an established Conn when its dial context is canceled?
How do you clear a connection deadline?