UDP in golang, Listen to a non-blocking call?

I am trying to create a two way street between two computers using UDP as the protocol. Maybe I do not understand the point of net.ListenUDP. Isn't that a blocking call? Waiting for a client connection?

addr := net.UDPAddr{ Port: 2000, IP: net.ParseIP("127.0.0.1"), } conn, err := net.ListenUDP("udp", &addr) // code does not block here defer conn.Close() if err != nil { panic(err) } var testPayload []byte = []byte("This is a test") conn.Write(testPayload) 
+7
go udp
source share
1 answer

It is not blocked because it is running in the background. You just read from the connection.

 addr := net.UDPAddr{ Port: 2000, IP: net.ParseIP("127.0.0.1"), } conn, err := net.ListenUDP("udp", &addr) // code does not block here defer ln.Close() if err != nil { panic(err) } var buf [1024]byte for { rlen, remote, err := conn.ReadFromUDP(buf[:]) // Do stuff with the read bytes } var testPayload []byte = []byte("This is a test") conn.Write(testPayload) 

Check this answer. It has a working example of UDP connections in go and some tips to make it work a little better.

+6
source share

All Articles