Problem: You want to create a UDP client to send data to a UDP server.
Solution: Use the Dial function in the net package to connect to a UDP server. Then use the Write method of the net.UDPConn interface to write data to the connection.
Creating a UDP client can be very straightforward, and it can look exactly like the TCP client, except the network string is udp instead of tcp:
func main() { conn, err := net.Dial("udp", ":9001") if err != nil { log.Fatal(err) } defer conn.Close() conn.Write([]byte("Hello from UDP client")) }
Try it out: set up a UDP listener using nc on one terminal. Use the -u flag to force nc to use UDP and the -l flag to listen for incoming connections:
$ nc -l -u 9001
Then run your UDP client on another terminal. You should see “Hello from UDP client” printed out on the server side.
This works for IPv4 and IPv6. To test this, you’ll use the -6 flag to force nc to use IPv6 on the server side:
$ nc -l -u -6 9001
If you run the same client you should see the same output.
You can also use the net.DialUDP function to create a UDP client:
func main() { raddr, err := net.ResolveUDPAddr("udp", ":9001") if err != nil { log.Fatal(err) } conn, err := net.DialUDP("udp", nil, raddr) if err != nil { log.Fatal(err) } defer conn.Close() _, err = conn.Write([]byte("Hello from UDP client")) if err != nil { log.Fatal(err) } }
The net.DialUDP function takes a net.UDPAddr as argument. First, use the net.ResolveUDPAddr function to resolve and create the address. Then use the net.DialUDP function to create the connection.
To write to the connection use the Write method of the net.UDPConn interface. The Write method takes a byte slice as an argument and returns the number of bytes written and an error.
【推荐】国内首个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