TCP server with goroutines
Three lines of substance: net.Listen opens the port. Accept loops. go handleConn spawns one goroutine per connection. Done.
func main() {
listener, err := net.Listen("tcp", addr)
if err != nil { log.Fatalf("listen: %v", err) }
defer listener.Close()
log.Printf("echo server listening on %s", addr)
for {
conn, err := listener.Accept()
if err != nil { continue }
go handleConn(conn)
}
}
func handleConn(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil { return }
conn.Write(buf[:n])
}
}The entire echo server. Per-conn goroutines mean multi-client from step 1.
Goroutines are ~2KB stacks. Spawning one per connection is the standard idiom. Python threads have ~8MB stacks and an OS-thread cost, so the same pattern is too expensive there. Go closes this gap structurally.
Quiz: Quiz
Loading practice…