How to Create a TCP Client in Go

Web
Use the `net.Dial` function from the standard library to establish a TCP connection, then wrap the returned `net.Conn` interface with `bufio` readers and writers for efficient I/O.

Use the net.Dial function from the standard library to establish a TCP connection, then wrap the returned net.Conn interface with bufio readers and writers for efficient I/O. This approach handles the underlying socket creation and connection logic automatically, allowing you to focus on sending and receiving data.

Here is a minimal example connecting to a local echo server:

package main

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

func main() {
	// Dial the TCP address
	conn, err := net.Dial("tcp", "localhost:9000")
	if err != nil {
		fmt.Println("Dial error:", err)
		os.Exit(1)
	}
	defer conn.Close()

	// Wrap connection for buffered I/O
	scanner := bufio.NewScanner(conn)
	writer := bufio.NewWriter(conn)

	// Send a message
	_, err = writer.WriteString("Hello, server!\n")
	if err != nil {
		fmt.Println("Write error:", err)
		return
	}
	if err := writer.Flush(); err != nil {
		fmt.Println("Flush error:", err)
		return
	}

	// Read response
	if scanner.Scan() {
		fmt.Println("Received:", scanner.Text())
	}
}

For production scenarios, you often need to handle timeouts and connection limits. Use net.Dialer to configure these parameters before dialing:

dialer := net.Dialer{
	Timeout:   5 * time.Second,
	KeepAlive: 30 * time.Second,
}

conn, err := dialer.Dial("tcp", "example.com:80")
if err != nil {
	// Handle connection failure
}

Always remember to close the connection using defer conn.Close() immediately after establishing it to prevent resource leaks. The net.Conn interface provides a unified way to handle both TCP and Unix domain sockets, so your logic remains consistent regardless of the transport. If you need to send binary data, you can write directly to conn using conn.Write() instead of the buffered writer, but buffering is generally recommended for text-based protocols to reduce system calls.