前言
同TCP通信类似,也需要用到原生包 net 来实现udp接口,同样分为客户端和服务端
客户端代码
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 9090,
})
if err != nil{
fmt.Printf("connect failed, err: %v\n", err)
return
}
for i:=0; i<100;i++{
_,err = conn.Write([]byte("Hello Server!"))
if err!=nil{
fmt.Printf("send data failed,err: %v\n", err)
return
}
result :=make([]byte,1024)
n, remoteAddr,err :=conn.ReadFromUDP(result)
if err!=nil{
fmt.Printf("receive data failed, err: %v\n",err)
}
fmt.Printf("receive from addr:%v data %v\n",remoteAddr,string(result[:n]))
}
}
服务端代码
package main
import (
"fmt"
"net"
)
func main() {
listen, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IPv4(0, 0, 0, 0),
Port: 9090,
})
if err != nil {
fmt.Printf("Listen failed, err: %v\n", err)
}
for {
var data [1024]byte
n, addr, err := listen.ReadFromUDP(data[:])
if err != nil {
fmt.Printf("Read failed from addr: %v ,err: %v\n", addr, err)
break
}
go func() {
fmt.Printf("addr: %v data: %v count: %v\n", addr, string(data[:n]), n)
_, err = listen.WriteToUDP([]byte("received success!"), addr)
if err != nil {
fmt.Printf("write failed,err: %v\n", err)
}
}()
}
}