Problem: You want to create a TCP client to send data to a TCP server.
Solution: Use the Dial function in the net package to connect to a TCP server.
Creating a TCP client is similar to creating a TCP server but even simpler. The main difference is that the client connects to a server instead of listening for connections:
func main () { conn , err := net . Dial ( "tcp" , ":9000" ) if err != nil { log . Fatal ( err ) } defer conn . Close () conn . Write ([] byte ( "Hello World from TCP client" )) }
First, connect to the server using the net.Dial function. Then write data to the connection; when you’re done you can close the connection.
The net.Dial function returns a net.Conn interface, which is a generic stream - oriented network connection. It is an abstraction of a network connection and has Read and Write methods, meaning it is both a Reader and Writer . In a TCP client, you will use this connection to write data to the server.
Use nc to listen on a port and see what the client sends:
$ nc - l 9000
Then run the client on another terminal:
$ go run main.go
On the nc terminal “Hello World from TCP client” prints out.
How about IPv6? You can use the - 6 flag to force nc to listen on IPv6:
$ nc - l - 6 9000
If you run the client again you will see the same output. Go TCP clients send out the data using both IPv4 and IPv6.
Just as you can create a TCP server using the net.ListenTCP and AcceptTCP functions, you can also create a TCP client using the net.DialTCP function:
func main () { addr , err := net . ResolveTCPAddr ( "tcp" , ":9000" ) if err != nil { log . Fatal ( err ) } conn , err := net . DialTCP ( "tcp" , nil , addr ) if err != nil { log . Fatal ( err ) } defer conn . Close () conn . Write ([] byte ( "Hello World from TCP Client" )) }
The net.DialTCP function takes a network string and two net.TCPAddr structs as arguments. You can create the address structs using the net.ResolveTCPAddr function. The first argument to net.DialTCP is the network, followed by the local address and the remote address. If the local address is nil, a local address is automatically chosen. If the remote address is nil, an error is returned.
标签:Creating,err,TCP,client,Client,address,Go,net,server From: https://www.cnblogs.com/zhangzhihui/p/17767275.html