Go offers a different family of functions that also allow you to develop TCP clients and servers. In this section, you will learn how to program a TCP client using these functions.
The name of the TCP client will be otherTCPclient.go, and it will be presented in four parts. The first code segment from otherTCPclient.go is as follows:
package main import ( "bufio" "fmt" "net" "os" "strings" )
The second code portion from otherTCPclient.go contains the following code:
func main() { arguments := os.Args if len(arguments) == 1 { fmt.Println("Please provide a server:port string!") return } CONNECT := arguments[1] tcpAddr, err := net.ResolveTCPAddr("tcp4", CONNECT) if err != nil { fmt.Println("ResolveTCPAddr:", err.Error()) return }
The net.ResolveTCPAddr() function returns the address of a TCP end point (type TCPAddr) and can only be used for TCP networks.
The third part of otherTCPclient.go contains the following code:
conn, err := net.DialTCP("tcp4", nil, tcpAddr) if err != nil { fmt.Println("DialTCP:", err.Error()) return }
The net.DialTCP() function is equivalent to net.Dial() for TCP networks.
The remaining code of otherTCPclient.go follows next:
for { reader := bufio.NewReader(os.Stdin) fmt.Print(">> ") text, _ := reader.ReadString(' ') fmt.Fprintf(conn, text+" ") message, _ := bufio.NewReader(conn).ReadString(' ') fmt.Print("->: " + message) if strings.TrimSpace(string(text)) == "STOP" { fmt.Println("TCP client exiting...") conn.Close() return } } }
Executing otherTCPclient.go and interacting with a TCP server will generate the following type of output:
$ go run otherTCPclient.go localhost:8001 >> Hello from otherTCPclient.go! ->: Hi from netcat! >> STOP ->: TCP client exiting...
For this example, the TCP server is supported by the netcat(1) utility, which is executed as follows:
$ nc -l 127.0.0.1 8001 Hello from otherTCPclient.go! Hi from netcat! STOP