create a tcp client on a specific port in go

To create a TCP client on a specific port in Go, you can use the net package. Here is an example code block that creates a TCP client on port 8080:

main.go
package main

import (
    "fmt"
    "net"
)

func main() {
    // Create a TCP client on port 8080
    conn, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer conn.Close()

    // Do something with the TCP client
    fmt.Fprintln(conn, "Hello, server!")
}
334 chars
20 lines

In the above code, net.Dial() is used to create a TCP client on localhost (change this to the IP address or hostname of the server you want to connect to) and port 8080.

Once the TCP client is created, you can use the conn variable to send and receive data to/from the server.

Don't forget to close the connection using the defer keyword to ensure that the connection is closed when the program exits.

related categories

gistlibby LogSnag