TCP Echo Server
Source: Custom
Topics: net.Listen, goroutines, io.Copy, context, SetDeadline
Problem
Implement a TCP server that echoes every byte it receives back to the sender.
Requirements:
New(addr string, idleTimeout time.Duration) *Server — create a server; bind happens in Start.
Start(ctx context.Context) error — bind, then serve; close the listener when ctx is cancelled; return nil on clean shutdown.
Addr() string — return the actual bound address (e.g. 127.0.0.1:54321); valid once Start has bound.
Started() <-chan struct{} — closed when the listener is bound, so callers can wait without polling.
- Handle each connection in a goroutine; enforce
idleTimeout via SetDeadline; wait for all goroutines before returning.
Type:
type Server struct { ... }
func New(addr string, idleTimeout time.Duration) *Server
func (s *Server) Start(ctx context.Context) error
func (s *Server) Addr() string
func (s *Server) Started() <-chan struct{}
Key concepts
- net.Listen + Accept loop:
ln.Accept() returns an error when the listener is closed — use that as the shutdown signal.
- Context shutdown: a goroutine waits on
ctx.Done() then calls ln.Close() to unblock Accept.
- SetDeadline: absolute deadline refreshed per-read/write using
conn.SetDeadline(time.Now().Add(timeout)), or set once after Accept.
- sync.WaitGroup: wait for all connection goroutines before returning from
Start.
Run
go test -v -race ./challenges/networking/tcp-echo/
Sign in to submit your solution.