UDP Server's code: package main import ( "fmt" "net" ) func main() { listener, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 9981}) if err != nil { fmt.Println(err) return } fmt.Printf("Local: <%s> \n", listener.LocalAddr().String()) data := make([]byte, 1024) for { n, remoteAddr, err := listener.ReadFromUDP(data) if err != nil { fmt.Printf("error during read: %s", err) } fmt.Printf("<%s> %s\n", remoteAddr, data[:n]) _, err = listener.WriteToUDP(data[0:n], remoteAddr) _, err = listener.WriteToUDP([]byte("world"), remoteAddr) if err != nil { fmt.Printf(err.Error()) } } }
UDP Client's Code: package main import ( "fmt" "net" "bytes" ) func main() { ip := net.ParseIP("127.0.0.1") srcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0} dstAddr := &net.UDPAddr{IP: ip, Port: 9981} conn, err := net.DialUDP("udp", srcAddr, dstAddr) if err != nil { fmt.Println(err) } defer conn.Close() conn.Write([]byte("hello")) buff := bytes.NewBuffer(make([]byte, 3)) fmt.Println(buff.ReadFrom(conn)) fmt.Printf("<%s>\n", conn.RemoteAddr()) } Why the UDP client blocked using BuffReadFrom method when read from a UDP connection? However, using bufio's Reader(the code is below) is ok. I am a newbie, feel really confused, so can anybody give me some explanation, thanks! My running environment is macOS Sierra and go version is go1.8.3 darwin/amd64 package main import ( "fmt" "net" "bufio" ) func main() { ip := net.ParseIP("127.0.0.1") srcAddr := &net.UDPAddr{IP: net.IPv4zero, Port: 0} dstAddr := &net.UDPAddr{IP: ip, Port: 9981} conn, err := net.DialUDP("udp", srcAddr, dstAddr) if err != nil { fmt.Println(err) } defer conn.Close() conn.Write([]byte("hello")) reader := bufio.NewReader(conn) rawbuff := make([]byte, 64) fmt.Println(reader.Read(rawbuff)) fmt.Println(string(rawbuff)) fmt.Printf("<%s>\n", conn.RemoteAddr()) } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.