To create a TCP server and accept incoming client connections in Go, you can follow these steps:
import (
"fmt"
"net"
)
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()
}
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)
}
}
handleConnection
function will handle each client connection, reading the data, processing it, and sending a response back to the client.