Use net.Listen to create a net.Listener that accepts incoming connections, then call Accept() to get a net.Conn for reading and writing data.
package main
import (
"fmt"
"io"
"log"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil && err != io.EOF {
log.Println(err)
return
}
fmt.Printf("Received: %s\n", string(buf[:n]))
conn.Write([]byte("Hello from server"))
}