ZhangZhihui's Blog  

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 ne⁠t.R⁠es⁠ol⁠veUD⁠PA⁠dd⁠r 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.

 

posted on   ZhangZhihuiAAA  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2019-10-16 PyCharm - Show modified files
 
点击右上角即可分享
微信分享提示