Server端bash
一、net.ListenUDP() 監聽UDP服務服務器
二、net.UDPConn.ReadFromUDP() 循環讀取數據 ide
三、net.UDPConn.WriteToUDP() 寫數據server
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端ci
一、net.Dial() 創建鏈接rem
二、net.UDPConn.Write() 寫數據string
三、net.UDPConn.ReadFromUDP() 回覆數據it
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])) } }