golang中的udp编程
1. udp server
package main import ( "fmt" "net" ) func main() { // udp server listenUdp, err := net.ListenUDP("udp", &net.UDPAddr{ IP: net.IPv4(127,0,0,1), Port: 8080, }) if err != nil { fmt.Println("ListenPacket fail err", err) return } defer listenUdp.Close() for { // 接收数据 var buf [1024]byte n, addr, err := listenUdp.ReadFromUDP(buf[:]) if err != nil { fmt.Println("ReadFromUDP fail err", err) continue } fmt.Printf("接收到客户端【%v】的数据:%s\n", addr, string(buf[:n])) // 发送数据 msg := "server发送回来的数据" + string(buf[:n]) num, err := listenUdp.WriteToUDP([]byte(msg), addr) if err != nil { fmt.Println("WriteToUDP fail err", num, err) continue } } }
2. udp client
package main import ( "fmt" "net" "strings" ) func main() { // udp client udpConn, err := net.DialUDP("udp", nil, &net.UDPAddr{ IP: net.IPv4(127,0,0,1), Port: 8080, }) if err != nil { fmt.Println("DialUDP fail err", err) return } defer udpConn.Close() for { // 发送数据 var data string fmt.Print("请输入要发送给服务器的数据:") fmt.Scanln(&data) if strings.ToUpper(data) == "Q" { break } sendData := []byte(data) _, err = udpConn.Write(sendData) if err != nil { fmt.Println("udp客户端Write fail err", err) return } // 接收数据 buf := make([]byte, 4096) n, remoteAddr, err2 := udpConn.ReadFromUDP(buf[:]) if err2 != nil { fmt.Println("udp客户端Read fail err", err2) return } fmt.Printf("data:%v, addr:%v\n", string(buf[:n]), remoteAddr) } }