Server端
1、net.ListenUDP() 监听UDP服务
2、net.UDPConn.ReadFromUDP() 循环读取数据
3、net.UDPConn.WriteToUDP() 写数据
package main
import (
"fmt"
"log"
"net"
)
func main() {
// 监听UDP服务
udpConn,err := net.ListenUDP("udp",&net.UDPAddr{
IP: net.IPv4(0,0,0,0),
Port: 9090,
})
if err != nil{
log.Fatal("Listen failed,",err)
return
}
// 循环读取消息
for {
var data [1024]byte
n,addr,err := udpConn.ReadFromUDP(data[:])
if err != nil{
log.Printf("Read from udp server:%s failed,err:%s",addr,err)
break
}
go func() {
// 返回数据
fmt.Printf("Addr:%s,data:%v count:%d \n",addr,string(data[:n]),n)
_,err := udpConn.WriteToUDP([]byte("msg recived."),addr)
if err != nil{
fmt.Println("write to udp server failed,err:",err)
}
}()
}
}
Client端
1、net.Dial() 建立连接
2、net.UDPConn.Write() 写数据
3、net.UDPConn.ReadFromUDP() 回复数据
package main
import (
"fmt"
"log"
"net"
)
func main() {
// 连接服务器
conn,err := net.DialUDP("udp",nil,&net.UDPAddr{
IP: net.IPv4(127,0,0,1),
Port: 9090,
})
if err != nil {
log.Println("Connect to udp server failed,err:",err)
return
}
for i:=0;i<10;i++{
// 发送数据
_,err := conn.Write([]byte(fmt.Sprintf("udp testing:%v",i)))
if err != nil {
fmt.Printf("Send data failed,err:",err)
return
}
//接收数据
result := make([]byte,1024)
n,remoteAddr,err := conn.ReadFromUDP(result)
if err != nil{
fmt.Printf("Read from udp server failed ,err:",err)
return
}
fmt.Printf("Recived msg from %s, data:%s \n",remoteAddr,string(result[:n]))
}
}
来源:oschina
链接:https://my.oschina.net/u/4366017/blog/4303352