How to create a TCP server and accept incoming client connections in Go?

To create a TCP server and accept incoming client connections in Go, you can follow these steps:

  1. Import the required packages:
import ( "fmt" "net" )
  1. Define a function to handle the client connections. This function will read and write data to the client:
func handleConnection(conn net.Conn) { // Read data from the client buffer := make([]byte, 1024) _, err := conn.Read(buffer) if err != nil { fmt.Println("Error reading:", err.Error()) } // Process the received data requestData := string(buffer) fmt.Println("Received data:", requestData) // Send a response to the client response := "Hello, client!" conn.Write([]byte(response)) // Close the connection conn.Close() }
  1. Create the TCP server:
func main() { fmt.Println("Starting server...") // Listen for incoming connections listener, err := net.Listen("tcp", "localhost:8080") if err != nil { fmt.Println("Error listening:", err.Error()) return } defer listener.Close() // Accept new client connections for { conn, err := listener.Accept() if err != nil { fmt.Println("Error accepting connection:", err.Error()) return } // Handle the client connection in a separate goroutine go handleConnection(conn) } }
  1. Run the server and check if it's accepting the incoming client connections. The handleConnection function will handle each client connection, reading the data, processing it, and sending a response back to the client.