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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2019-10-16 PyCharm - Show modified files