create a tcp client in go

Here's a basic TCP client implementation in Go using the standard net package:

main.go
package main

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

func main() {
    // Replace host:port with the address of the TCP server you want to connect to
    conn, err := net.Dial("tcp", "host:port")
    if err != nil {
        fmt.Println("Error connecting:", err)
        os.Exit(1)
    }
    defer conn.Close()
    
    // Send data to the server
    message := []byte("Hello, server!")
    _, err = conn.Write(message)
    if err != nil {
        fmt.Println("Error sending data:", err)
        os.Exit(1)
    }
    
    // Read data from the server
    buffer := make([]byte, 1024)
    bytesRead, err := conn.Read(buffer)
    if err != nil {
        fmt.Println("Error receiving data:", err)
        os.Exit(1)
    }
    
    // Print the server's response
    fmt.Println("Server response:", string(buffer[:bytesRead]))
}
826 chars
37 lines

This code establishes a TCP connection to a server at the address host:port, sends a message to the server, reads the server's response, and prints it to the console. It's a good starting point for building more elaborate TCP clients in Go.

gistlibby LogSnag