// +build ignore package main import ( "bufio" "fmt" "io" "log" "net" ) func main() { // listening on tcp://0.0.0.0:8080 ln, err := net.Listen("tcp", "0.0.0.0:8080") if err != nil { log.Fatalln(err) } fmt.Println("listening on", ln.Addr()) // assign a unique id to each incoming connection for id := 0; ; id++ { if conn, err := ln.Accept(); err == nil { fmt.Printf("client[%d] connected from %s\n", id, conn.RemoteAddr()) // handle the connection go echo(conn, id) } } } func echo(conn io.ReadWriteCloser, id int) { // close the conn on EOF defer func() { fmt.Printf("client[%d] disconnected: read: EOF\n", id) conn.Close() }() // for each line, do ... for scanner := bufio.NewScanner(conn); scanner.Scan(); { // get line line := scanner.Text() // echo back to client if _, err := io.WriteString(conn, fmt.Sprintln(line)); err != nil { fmt.Printf("client[%d] disconnected: write: %s\n", id, err.Error()) break } // server-side log fmt.Println(fmt.Sprintf("client[%d]: %s", id, line)) } }