Connect and accept with net.Conn and Listener
Connect and accept with net.Conn and Listener
A Listener accepts incoming stream connections; net.Conn represents one connection and implements Reader and Writer. A listener and accepted connections have independent lifetimes. Use only loopback 127.0.0.1 with port 0 (OS-selected port) in these labs. A short deadline bounds I/O; check errors and close both endpoints. Panic here stops a small demonstration, not a production server error policy.
package main
import ( "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(3 * time.Second))) c, e := net.DialTimeout("tcp4", l.Addr().String(), time.Second) check(e) defer c.Close() s, e := l.Accept() check(e) defer s.Close() check(c.SetDeadline(time.Now().Add(time.Second))) check(s.SetDeadline(time.Now().Add(time.Second))) _, e = c.Write([]byte("OK")) check(e) b := make([]byte, 2) _, e = io.ReadFull(s, b) check(e) fmt.Println(string(b))}ListenTCP permits an accept deadline; DialTimeout limits establishment. Dial returns the client Conn, Accept returns the server Conn. ReadFull obtains exactly two bytes or an error. The small write fits the local socket buffer; real arbitrary-sized duplex traffic may require concurrent reading and writing.
Expected output:
OKUse an in-memory connection pair
package main
import ( "fmt" "io" "net" "time")
func check(e error) { if e != nil { panic(e) }}func main() { a, b := net.Pipe() defer a.Close() defer b.Close() check(a.SetDeadline(time.Now().Add(time.Second))) check(b.SetDeadline(time.Now().Add(time.Second))) done := make(chan error, 1) go func() { _, e := a.Write([]byte("hi")); done <- e }() buf := make([]byte, 2) _, e := io.ReadFull(b, buf) check(e) check(<-done) fmt.Println(string(buf))}net.Pipe has no internal buffering: a write waits for a matching read. It is useful for deterministic connection tests but is not a TCP socket. In real servers closing the listener stops Accept; already accepted connections require their own cleanup.
Expected output:
hiTry it locally
Use net.Pipe to send three bytes YES, read them fully and wait for the sender.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Networking 02: Connect and accept with net.Conn and Listener
Check the lesson objective before moving on.
What does Accept return on success?
Why use a goroutine with net.Pipe.Write?