TCP Echo Accept Loop With Deadlines

net.Listen plus an Accept loop gives each connection a goroutine that echoes bytes; SetReadDeadline bounds hung clients and errors.Is(io.EOF) detects closes.

GoResilience

Code

gosnippet
58 lines
package main

import (
	"errors"
	"fmt"
	"io"
	"net"
	"time"
)

func echo(conn net.Conn) {
	defer conn.Close()
	// 读截止:异常连接挂住不会拖垮整个进程
	if err := conn.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil {
		return
	}
	buf := make([]byte, 512)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			// errors.Is 区分干净关闭(EOF)与真实读错误
			fmt.Println("read ended, clean:", errors.Is(err, io.EOF))
			return
		}
		if _, err := conn.Write(buf[:n]); err != nil {
			return
		}
	}
}

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil { panic(err) }
	defer listener.Close()
	fmt.Println("listening on", listener.Addr())

	done := make(chan struct{})
	go func() {
		defer close(done)
		conn, err := net.Dial("tcp", listener.Addr().String())
		if err != nil {
			return
		}
		defer conn.Close()
		if _, err := conn.Write([]byte("ping")); err != nil {
			return
		}
		buf := make([]byte, 32)
		if n, err := conn.Read(buf); err == nil {
			fmt.Println("echoed:", string(buf[:n]))
		}
	}()

	conn, err := listener.Accept()
	if err != nil { panic(err) }
	echo(conn)
	<-done
}

How the snippet works

Under the hood: the functions echo and main.

Repetition is confined to for — the rest of the file is straight-line. The 7 err != nil branches are handled two different ways: the setup checkpoints in main (net.Listen, listener.Accept) call panic(err), while the other 5 — SetReadDeadline, the echo read, the echo write, net.Dial, the client write — quietly return, so a single bad connection or a failed dial never takes the process down. The echo read is not a bare swallow either: errors.Is(err, io.EOF) separates the client’s clean close from a real read fault, and which one it was is printed as read ended, clean:. The goroutine hands nothing back — done is a chan struct{} used purely as a completion signal (defer close(done) inside the goroutine, <-done at the end of main), not a result channel. Cleanup is attached with defer, so it runs on every exit path of the function.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.
  • Only net.Listen and Accept abort through panic(err); the per-connection and client-side paths return, and the normal end of a client session arrives as io.EOF — recognized with errors.Is, not treated as a failure.

Using it

One line captures it: func echo(conn net.Conn)

Running the file prints listening on 127.0.0.1:<port>, then echoed: ping, then read ended, clean: true once the client goroutine closes its side.

The demo flow inside main is echo — run the file to see it end to end.

Key statements

if err != nil { panic(err) }
done := make(chan struct{})
if err != nil {
	// errors.Is 区分干净关闭(EOF)与真实读错误
	fmt.Println("read ended, clean:", errors.Is(err, io.EOF))
	return
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does TCP Echo Accept Loop With Deadlines print when run?
Run it as a complete program — the output lines carry labels such as `read ended, clean:`, `listening on`, `echoed:`.