How to implement a TCP client that sends and receives data in Go?

To implement a TCP client that sends and receives data in Go, you can follow these steps:

Step 1: Import the required packages

import ( "fmt" "net" "os" )

Step 2: Define the server address and port

const ServerAddr = "127.0.0.1:1234"

Step 3: Create a TCP connection to the server

conn, err := net.Dial("tcp", ServerAddr) if err != nil { fmt.Println("Error connecting:", err) os.Exit(1) } defer conn.Close()

Step 4: Send data to the server

data := "Hello, server!" conn.Write([]byte(data))

Step 5: Receive data from the server

buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { fmt.Println("Error reading:", err) os.Exit(1) } receivedData := string(buffer[:n]) fmt.Println("Server response:", receivedData)

Complete example:

package main import ( "fmt" "net" "os" ) const ServerAddr = "127.0.0.1:1234" func main() { conn, err := net.Dial("tcp", ServerAddr) if err != nil { fmt.Println("Error connecting:", err) os.Exit(1) } defer conn.Close() data := "Hello, server!" conn.Write([]byte(data)) buffer := make([]byte, 1024) n, err := conn.Read(buffer) if err != nil { fmt.Println("Error reading:", err) os.Exit(1) } receivedData := string(buffer[:n]) fmt.Println("Server response:", receivedData) }

Make sure to replace ServerAddr with the actual address and port of your server.