listener, err := net.Listen("tcp", ":8080") if err != nil { log.Fatal(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } // handle connection in a separate goroutine go handleConn(conn) } func handleConn(conn net.Conn) { defer conn.Close() // read from and write to the connection }
listener, err := net.Listen("tcp", ":8080") if err != nil { log.Fatal(err) } defer listener.Close() conns := make(chan net.Conn) for i := 0; i < 10; i++ { go func() { for conn := range conns { // handle connection in a separate goroutine go handleConn(conn) } }() } for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } conns <- conn } func handleConn(conn net.Conn) { defer conn.Close() // read from and write to the connection }This example uses a goroutine pool to handle incoming connections concurrently, improving the server's scalability. The package being used is still the "net" package.